So, it's a little trick to use the '&&' conditional instead of an 'if' block. For example:
[[ -n $var ]] && { echo echo $var echo }
It's really just syntactic sugar, because it looks cooler (in a way) than:
if [[ -n $var ]]; then echo echo $var echo fi
But if you use the '&&' conditional a lot, you could be surprised when the '-e' option causes your script to exit when it shouldn't!
Here's a trivial example. Let's say we have a 'while' loop that reads some lines of input and does something special for empty lines:
echo $'one\ntwo\nthree' | while read input; do echo "input: $input" if [[ -z $input ]]; then echo "empty $input" # do some special processing for an empty line... fi done # Do a bunch more stuff... echo "Continuing processing..."
This works fine. But let's change it to use the '&&' operator instead of an 'if' block:
echo $'one\ntwo\nthree' | while read input; do echo "input: $input" [[ -z $input ]] && { echo "empty $input" # do some special processing for an empty line... } done # Do a bunch more stuff... echo "Continuing processing..."
This will fail! And it's only because we have the '-e' option set! The reason is that the 'while' command uses the exit status of the last command it ran. In this particular case, the last command was the '[[' command, which failed because the last line of input was not empty.
This also means that if the '[[' command is the last command in your script, the script itself may exit with an error status when there is actually nothing wrong.
Using the 'if' command is safer, because it wraps the '[[' command, uses that exit status for the conditional check, but returns its own successful exit status. So the '-e' option will not cause an 'if' to fail the whole script.
No comments:
Post a Comment