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

4 Responses to “Command Substitution and Exit Status”

  1. nic1138 Says:

    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? :]

  2. Rude awakening « crashingdaily Says:

    [...] 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 [...]

  3. Brock Noland Says:

    @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

  4. Brock Noland Says:

    > where in the manual can I find about this [[ ! -z … ]] thing? :]

    No problem, man test covers all the tests available.

    Brock

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.