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 display error message.
Old way
You can write something as follows:
cat /etc/shadow 2>/dev/null
if [ $? -ne 0 ]; then echo "Failed to open file"; exit1 ; fi
New way - OR || control operator
However you can use control operator || (or lists). It has the form:
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 error message. Another option is to create die function:
#!/bin/bash
function die(){
echo $1
exit 1
}
# ...
# ... other code
cat /etc/shadow 2>/dev/null || die “Failed to open file”
# rest of scriptAND && control operator
Similarly you can use AND (&&) control operator. It has the form:
command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero.
$ cat /etc/shadow 2>/dev/null && echo "I can open /etc/shadow file"
You can combine both to produce useful message in a script:
#!/bin/bash
...
tar -zcf /dev/st0 /data2 && echo "/data2 added to backup device" || echo "Warning: Cannot add /data2 to backup device"
....
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 0 comments… add one now }