UNIX commands ALWAYS have an exit code. 0 (zero) is always success, any other exit code means failure for some reason or another.
All UNIX systems have a built in variable $? to get the exit code of the previous command. Let's see how it works
[biff@home ~]$ ls > /dev/null [biff@home ~]$ echo $? 0 [biff@home ~]$
[biff@home ~]$ cat /etc/shadow cat: /etc/shadow: Permission denied [biff@home ~]$ echo $? 1 [biff@home ~]$ [biff@home ~]$ cat /etc/shadow 2> /dev/null [biff@home ~]$ echo $? 1 [biff@home ~]$first I tried to cat a file I didn't have permissions to and the command failed. Then I did the same thing but redirected the error with "2>" to /dev/null
#!/bin/sh
FILE="/etc/shadow"
cat $FILE 2> /dev/null
if [ $? -ne 0 ]
then
echo "checking $FILE failed .. exiting"
exit 1
fi
I check to see if I was able to use cat on a file by checking the return code in my shell script. If I wasn't able to, I leave a nice message and exit
#!/bin/sh
$FILE=/etc/shadow
function chkerr_exit(){
$@ 2> /dev/null
if [ $? -ne 0 ]
then
# epic fail.
echo "failed executing $@ "
exit 1
fi
}
chkerr_exit "cat $FILE"
chkerr_exit "rm $FILE"
exit 0
if [ ! -d someDirectory ]
then
echo "directory does not exist"
exit 1
fi
if [ -f /etc/passwd ]
then
cat /etc/passwd
fi
In this case I tested to see if a directory didn't exist and if the /etc/passwd file was a regular file. Using these methods will help you avoid errors at runtime