5

I have a bash script running two subscripts t1 and t2. Both t1 and t2 are background processes and t1 will raise an error. How do I catch this error and exit the whole script completely?

#!/bin/bash
set -e

error1() {
    echo "exit whole script!!!"
    exit 1
}

# this script will rise an error
./t1.sh &
pid1=$!


./t2.sh &
pid2=$!


wait $pid2

if [ $pid2 -eq 0 ]; then
    trap 'error1' ERR
fi


wait $pid1

if [ $pid1 -eq 0 ]; then
    trap 'error1' ERR
fi
Michael
  • 1,398
  • 5
  • 24
  • 40

1 Answers1

3

Idea is to get the return code of the background process and to decide accordingly.

#!/bin/bash
set -e
#set -o pipefail

error1() {
    echo 'err'
    exit 1
}

# this script (process) will rise an error
./t1.sh &
pid_1=$!  # Get background process id


# Getting the process-id of the second process
./t2.sh &
pid_2=$!  

# If either of the processes crash with a non-zero error code, wait returns  
# '0' and the 'if' condition fails.

if  wait $pid_1 && wait $pid_2
then
    echo -e "Processes termination successful"
else
    trap 'error1' ERR  # Either of P1 or P2 has terminated improperly
fi
Inian
  • 80,270
  • 14
  • 142
  • 161
  • Is it possible to run t1 and t2 as background process, and terminate script when either one of them raises an error? – Michael Apr 27 '16 at 10:58
  • Yes, it is possible. Add a bash condition to `wait` on both the process id's and do the corresponding actions. – Inian Apr 27 '16 at 11:41
  • I tried your suggestion but I still can't get it to work, it didn't go to error1(). Can you kindly have a look at it? I have edited the code above. Thank you so much – Michael Apr 27 '16 at 12:44
  • Updated the answer, accept the same if it is useful. – Inian Apr 27 '16 at 13:21
  • thanks, but I can't get it work. I tried to raise error in t1.sh, but the error is not caught. Codes of t1.sh #!/bin/bash set -e run1() {return 1} run1 – Michael Apr 27 '16 at 14:56
  • `return` won't work in the context of returning error code from a program. You need to use `exit` like `exit 1` to return a non-zero code in bash – Inian Apr 27 '16 at 14:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110403/discussion-between-inian-and-michael). – Inian Apr 27 '16 at 15:05