Howto display error message instantly when command fails

last updated in Categories Debian Linux, FreeBSD, Linux, OpenBSD, RedHat/Fedora Linux, Shell scripting, Suse Linux, Ubuntu Linux, UNIX

While writing a shell script you may need to display an error message. For example, if you failed to open /etc/passwd file you want to show an error message.


The old method

You can write something as follows on bash using the if statement to test a condition

cat /etc/shadow 2>/dev/null
if [ $? -ne 0 ]; then echo "Failed to open file"; exit 1 ; fi

The new way: OR || control operator

However, you can use the control operator || (or lists). It has the form as follows:
command1 || command2
command2 is executed if and only if command1 returns a non-zero exit status. For example:
$ cat /etc/shadow 2>/dev/null || echo "Failed to open file"
This way you display an error message. Another option is to create die shell function:

function die(){
 echo "$1"
 exit 1
# ...
# ... other code
cat /etc/shadow 2>/dev/null || die "Failed to open file"
# rest of my script

AND (&&) control operator

Similarly you can use AND (&&) control operator. It has the form/syntax:
command1 && command2
The command2 is executed if, and only if, command1 returns an exit status of zero. For example:
$ cat /etc/shadow 2>/dev/null && echo "I can open /etc/shadow file."
You can combine both to produce useful message in a script:

tar -zcf /dev/st0 /data2 && echo "/data2/ added to backup device" || echo "Warning: Cannot add /data2/ to backup device."


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.