Howto display error message instantly when command fails

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."

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum