I know a little of bash
return codes on successful/failure conditions, but I was experimenting a little with wait
on background processes on couple of scripts on if
condition and I was surprised to see the behavior on the return error codes 0
for success and non-zero for failure cases.
My scripts:-
$cat foo.sh
#!/bin/bash
sleep 5
$cat bar.sh
#!/bin/bash
sleep 10
$cat experiment.sh
./foo.sh &
pid1=$!
./bar.sh &
pid2=$!
if wait $pid1 && wait $pid2
then
echo "Am getting screwed here!"
else
echo "Am supposed to be screwed here!"
fi
Run the script as it is and getting the output as Am getting screwed here!
instead of Am supposed to be screwed here!
$./experiment.sh
Am getting screwed here!
Now modifying the scripts to forcefully return exit codes using exit
in both foo.sh
and bar.sh
$cat foo.sh
#!/bin/bash
sleep 5
exit 2
$cat bar.sh
#!/bin/bash
sleep 10
exit 17
And am surprised to see the output as
$./experiment.sh
Am supposed to be screwed here!
Apologize for the detailed post, but any help appreciated. The man page for reference:- http://ss64.com/bash/wait.html
That's correct behavior. The exit status of wait
(when called with a single process ID) is the exit status of the process being waited on. Since at least one of them has a non-zero exit status, the &&
list fails and the else
branch is taken.
The rationale is that there is one way (0) for a command to succeed but many ways (any non-zero integer) for it to fail. Don't confuse bash
's use of exit statuses with the standard Boolean interpretation of 0 as false and nonzero as true. The shell if
statement checks if its command succeeds.