Put simply, you should not assume that code executed in an exit path will not cause an error itself. This is not specific to shell script, but just good programming advice in general.
By using echo ‘foo’ && exit
, you will only exit if the echo 'foo'
succeeds. The likelihood of that failing is indeed exceedingly low, but you should not count on that, especially when the cost of doing it right is so small. This becomes significantly more important when you have a more complicated exit path that may invoke other functions in your code and it’s not obvious that your exit path will only invoke ‘mostly safe’ stuff like echo
, but it’s generally good form to use ‘correct’ code in all cases so you get in the habit of doing it properly (and so your colleagues know what to expect).
If, for some reason, you need that to be one line (I would argue this should never be the case though), the correct syntax is echo 'foo' ; exit
, which causes the parser to treat the two commands as if they were on separate lines.
As an aside, in your conditional, you should almost always prefer either:
if [[ -n $VAR_A && -n $VAR_B ]]; then
which is bash-specific but more efficient than what you have currently, or:
if [ -n "$VAR_A" ] && [ -n "$VAR_B" ]; then
which will work in a semantically equivalent manner in any POSIX-compliant shell.
echo
doesn't work for whatever reason, theexit 1
will not fire. Not only will it not return the intended exit code (upon which the caller may depend), but the shell will continue to run whatever is below the if statement. I doubt that is what you intended, is it?