George V. Reilly

Bash: echo success of previous command

C-like languages have a ternary operator, cond ? true_re­sult : false_re­sult. Python has true_re­sult if cond else false_re­sult. Bash doesn’t have a ternary operator, but there are various workarounds.

I wanted to print succeeded or failed based on the exit code of the previous command in a shell script. In Unix, all programs exit with an integer status code. Successful programs exit with 0; all other values, positive or negative, indicate failure. In Bash, the status code of the previous program is held in $?.

some/command or-other fer example

STATUS="$([ "$?" == 0 ] && echo 'succeeded' || echo 'failed')"
echo "Results: $STATUS"

There are other ways to handle this.

blog comments powered by Disqus
Movember 2016 » « Trump Inauguration