Command Substitution and Exit Status
March 20th, 2008
I realized today, that it may not be obvious that command substitution can be done in parallel with compound commands. Meaning that variable assignment and tests can be done inline. For example, the exit status of the command inside an assignment operation is the exit value of the assignment operation:
$ val=$( false ); echo $? 1 $ val=$( true ); echo $? 0
I used this today when I wrote a long running test which slept 60 seconds between loops. Midway through the test I decided I wanted it to sleep only 15 seconds. Here was my command to resolve this situation without stopping my test:
$ while :; do p=$(pgrep sleep) && sleep 15 && kill $p; sleep 1;done
If pgrep finds and any “sleep” process, the command sleeps 15 seconds and then kills the previously described process. After which it sleeps one second and looks for more “sleep” processes to kill. I am assigning the output of pgrep to the variable p and using pgrep’s exit status to decided whether any processes need to be killed.
The alternative would have been something like:
$ while :; do p=$(pgrep sleep); [[ ! -z "$p" ]] && sleep 15 && kill $p; sleep 1;done


March 21st, 2008 at 11:36 am
This one was great!… It’s like the C behavior, right?…
Now, I must ask, where in the manual can I find about this [[ ! -z ... ]] thing? :]
March 21st, 2008 at 4:09 pm
[...] Tips BASH Cures Cancer has yet another interesting post this week. This one, entitled “Command Substitution and Exit Status“, leverages the exit status returned from a BASH sub-shell. That alone is a useful tip but [...]
March 21st, 2008 at 8:46 pm
@nic1138,
> It’s like the C behavior, right?
Yes, its like kind of like C, PHP and some other languages. Its slightly different in that its the exit value of the command inside the Command Substitution. Whereas with C and PHP I believe its the value of the variable.
Brock
March 21st, 2008 at 8:47 pm
> where in the manual can I find about this [[ ! -z … ]] thing? :]
No problem, man test covers all the tests available.
Brock