3

I know this is a common question and I have even seen answers to it before, but I cannot remember what they were nor find them.

#!/usr/bin/env bash

set -m         # allow for job control
EXIT_CODE=0    # exit code of overall script

function foo() {     
     for job in `jobs -p`; do
         echo "PID => ${job}"
         wait ${job} ||  { echo "At least one test failed with exit code => $?" ; EXIT_CODE=1; }
     done
}

trap 'foo' CHLD

My question concerns this line:

wait ${job} ||  { echo "At least one test failed with exit code => $?" ; EXIT_CODE=1; }

If wait ${job} yields a non-zero exit code I'd like to echo out the statement and then do an assignment (assigning 1 to EXIT_CODE).

I don't believe my syntax is correct. I am not getting any obvious errors, but I am pretty certain it's not correct because the statement is not being echoed. But I am still exiting with an exit code of 1.

  • 2
    That wait... line already looks good to me. I assume you've not provided your entire script, though, so there's only the posted context to review. – roaima Feb 13 '17 at 13:07
  • stackoverflow.com/help/mcve – user147505 Feb 14 '17 at 1:58
2

Are you sure that wait is terminating with a non-zero exit status? Consider, for example:

false || { echo "At least ..."; EXIT_CODE=1; }

That will generate the message and set EXIT_CODE appropriately.

I initially thought this was what you were looking for:

wait ${job} || ( echo "At least ..."; EXIT_CODE=1 )

The problem with this approach is that the content of (...) is executed in a subshell – the change to the value of EXIT_CODE will be local to that subshell (i.e., it won't be visible when you try to read it later).

Consider, for example:

EXIT_CODE=0
false || ( echo "At least ..." ; EXIT_CODE=1; echo "code: ${EXIT_CODE}" )
echo "final code: ${EXIT_CODE}"

The output will be:

At least ...
code: 1
final code: 0

I'd suggest not trying to be too fancy:

if ! wait ${job}; then
    echo "At least ..."
    EXIT_CODE=1;
fi
  • Ok thanks, why the () instead of the {} though? – Alexander Mills Feb 13 '17 at 20:34
  • should it be if [[ ! wait ${job} ]] ; then – Alexander Mills Feb 14 '17 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.