Set -e and background process

In my script, I set set -e to stop processing if an error occurs. It works well for all teams running in the foreground, but some of my commands must run in parallel in the background. Unfortunately, if the background process crashes, the script does not stop, although the flag is set -e .

An example of using the foreground process.

 #!/bin/bash set -e ls -l no_file sleep 100 

The background process example does not work.

 #!/bin/bash set -e ls -l no_file & sleep 100 

How to handle background process crashes?

+5
source share
1 answer

Running a command asynchronously (with & ) always returns a completion status of 0. To get the actual exit status of a command, use the built-in wait . A simple example:

 $ (sleep 5; ls -l nofile) & [1] 3831 $ echo $? 0 $ wait -n ls: cannot access 'nofile': No such file or directory [1]+ Exit 2 ( sleep 5; ls --color=auto -l nofile ) $ echo $? 2 

wait -n waiting for some child process (which can be very useful). If you want to wait for a specific process, you can capture the PID when it starts - in the special variable $! - then wait by PID:

 $ (sleep 5; ls -l nofile) & $ myjobpid=$! $ # do some other stuff in parallel $ wait ${myjobpid} ls: cannot access 'nofile': No such file or directory [1]+ Exit 2 ( sleep 5; ls --color=auto -l nofile ) 

The relevant section of the Bash manual is called β€œJob Management”

+5
source

Source: https://habr.com/ru/post/1264562/


All Articles