0

I have a shell script which I want to exit based on the value of a variable ERROR_COUNT. I can either write

if [ ${ERROR_COUNT} -gt 0 ]
then
    echo "Exiting unsuccessfully";
    exit 1;
fi
echo "Exiting successfully";
exit;

or

if [ ${ERROR_COUNT} -gt 0 ]
then
    echo "Exiting unsuccessfully";
    exit 1;
else
    echo "Exiting successfully";
    exit;
fi

Is there any problem with either of the approaches?

  • As far as I understand the functionality there shuldn't be problems with the given approaches. – U880D Apr 16 '18 at 12:11
2

There is no technical difference between the two ways of writing the branches in terms of what would happen. It's a matter of style and personal preference.

Some developers dislike having an unconditional exit in the else branch of an if statement if the first branch is exiting.

I would probably write the code as

if [ "$ERROR_COUNT" -ne 0 ]; then
    echo 'There were errors' >&2
    exit 1
fi
# echo 'No errors' >&2

Note the removed semicolons, the quoted variable expansion, and the removed last exit (which is implicit at the end of the script. I changed the test to -ne 0 from -gt 0 because it's clearer (at least to me).

I've also changed the output of the two diagnostic messages so that they go to the standard error stream (and improved them in a way that would be more useful to the user). It is debatable whether the last echo should be there at all since there is really nothing to report other than successful execution (I commented it out).

  • Why were the semicolons removed? – Nitish Apr 16 '18 at 12:21
  • @Nitish Semicolons are command delimiters, just like newlines. In almost every case where you have a semicolon, you can replace it with a newline. Note that I also introduced a semicolon to get the then on the same line as the if. – Kusalananda Apr 16 '18 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.