Displaying Error Messages When Failures Occur

Problem

You need your shell script to be verbose about failures. You want to see error messages when commands don’t work, but if statements tend to distract from the visual flow of statements.

Solution

A common idiom among some shell programmers is to use the || with commands to spit out debug or error messages. Here’s an example:

cmd || printf "%b" "cmd failed. You're on your own\n"

Discussion

Similar to how the && didn’t bother to evaluate the second expression if the first was false, the || tells the shell not to bother to evaluate the second expression if the first one is true (i.e., succeeds). As with &&, the || syntax harkens back to logic and C Language where the outcome is determined (as true) if the first expression in A OR B evaluates to true—so there’s no need to evaluate the second expression. In bash, if the first expression returns 0 (i.e., succeeds) then it just continues on. Only if the first expression (i.e., exit value of the command) returns a non-zero value must it evaluate the second part, and thus run the other command.

Warning—don’t be fooled by this:

cmd || printf "%b" "FAILED.\n" ; exit 1

The exit will be executed in either case! The OR is only between those two commands. If we want to have the exit happen only on error, we need to group it with the printf so that both are considered as a unit. The desired syntax would be:

cmd || { printf "%b" "FAILED.\n" ; exit 1 ; }

Due to an oddity of bash syntax, the semicolon after the last command and just before the } is required, and that closing brace must be separated by whitespace from the surrounding text.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.