Search code examples
functionshexit-code

How to output the excit code after the function finished


If in a shell script. There are two function with loop, and I run both function in the script and put both in the background.

For example:

#!/bin/bash

function a {
  for 1 in 2; do
    if 3.sh; then
       echo 'done'
    else
       exit 1
    fi
  done
}

function b {
  for a in b; do
    if c.sh; then
       echo 'done'
    else
       exit 1
    fi
  done
}

a &
b &

Now since both functions are in background, once I run the script it will be completed right away. What I expected was to capture the exit code of the script so if anything wrong happened during loop a and b I can become acknowledged.

My another concern is that if anything happened during loop a, the script will be terminated right away (since exit code 1 is given), so b got terminated as well even if it's innocent.


Solution

  • If you wait on a background job, the exit status of wait will be the exit status of the job.

    a & a_pid=$!
    b & b_pid=$!
    
    wait $a_pid
    a_status=$?
    wait $b_pid
    b_status=$?
    

    You might object that if b finishes before a, then you have to wait to get b's status. That might be a problem, but only if you have anything else to do. Regardless of which job finishes first, the time it takes for both to complete is the same. (If b does finish first, then wait $b_pid will exit immediately once it is run.)