0

I have written a script like this:

error = 0

do_background() {
  command $1 || {
    echo "command has failed with status $?"
     ((error++));
  }
}

for i in 1..20; do
  do_background $i &
done
wait
if [[ $error != 0 ]]; then
  echo "Detected $error errors"
  exit 1
fi

If I run it with the -x option here is the result:

+ command 1
+ echo 'command has failed with status 1'
command has failed with status 1
+ (( error++ ))
+ [[ 0 != 0 ]]

My question is why error isn't greater than zero.

Ivan
  • 6,188
  • 1
  • 16
  • 23
david.perez
  • 6,090
  • 4
  • 34
  • 57
  • I am not sure that error value is shared within processes. – Itération 122442 Aug 29 '23 at 11:05
  • Does this answer your question? [bash background process modify global variable](https://stackoverflow.com/questions/13207292/bash-background-process-modify-global-variable) – pjh Aug 29 '23 at 11:33
  • See [BASH - How to get variable from the script that runs in the background](https://stackoverflow.com/q/15696382/4154375) and [Setting environment variables with background processes running in parallel](https://stackoverflow.com/q/64540852/4154375). – pjh Aug 29 '23 at 11:34
  • The variable `error` in your function is in a different process than the variable `error` in the parent process. – user1934428 Aug 29 '23 at 13:31

1 Answers1

1

Yes because the function runs in a subshell, so any changes made to the error variable inside the function will not be reflected in the parent shell. so, the error variable remains 0 in the parent shell, in this case you can use return statement in the do_background function to indicate if the command failed, and then check the return value of the function in the main script and the do_background function returns 1 if the command fails.

something like this:

error=0

do_background() {
  command $1 || {
    echo "command has failed with status $?"
    return 1
  }
}

for i in {1..20}; do
  do_background $i &
  pids[$i]=$!
done

for pid in "${pids[@]}"; do
  wait $pid || ((error++))
done

if [[ $error != 0 ]]; then
  echo "Detected $error errors"
  exit 1
fi
Freeman
  • 9,464
  • 7
  • 35
  • 58