exit codes

exit codes
When a command completes execution it provides an exit code. You can have exit codes between 0-255.  The exit code is created when a command returns control to the parent process.  Usually "0" represents success in the script and failure is indicated by any other numerical value.


Lesson 5 | Lesson 7



All commands will have exit codes.  In this example when the command "cd /var" is successful and issues an exit code of "0" the second command executes.

cd /var && ls

In the same way an exit code that is different than "0" indicates failure and it too can be used in writing code.  In this example you try to move to a directory, if it has not been created it exits with an error and as a result the second command runs to create the directory.

cd /home/accounting || mkdir /home/accounting

The script that follows checks for a user to see if they are in the /etc/passwd file.  One of the aspects of this code is to provide an exit code of “1” when the user is not in the /etc/passwd file.

user.sh

#!/bin/sh
grep "^${1}:" /etc/passwd > /dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "Cannot find user ${1} in /etc/passwd"
exit 1
fi
USERNAME=`grep "^${1}:" /etc/passwd|cut -d":" -f1`
NAME=`grep "^${1}:" /etc/passwd|cut -d":" -f5`
HOMEDIR=`grep "^${1}:" /etc/passwd|cut -d":" -f6`

echo "USERNAME: $USERNAME"
echo "NAME: $NAME"
echo "HOMEDIR: $HOMEDIR"


grep "^${1}:" /etc/passwd > /dev/null 2>&1
In this line grep is searching for the user that was entered when the script was run, that becomes the first position and is used throughout the script.  Note that the “^” indicates the start of the line.  Once the script discovers this information, the stdout and stderr are sent to /dev/null so as not to be shown on the screen.

if [ "$?" -ne "0" ]; then
echo "Cannot find user ${1} in /etc/passwd"
exit 1
fi

knowledge Increase Your Knowledge About the cut Command

Flow control provides you a way to specify a condition to occur, otherwise another condition will occur in the script.      You can test a condition and create options based on whether the situation is true and if not what happens next.

The “fi” determines the if block, so it starts with “if” and ends with “fi”.

 


Copyright CyberMontana Inc. and BeginLinux.com
All rights reserved. Cannot be reproduced without written permission. Box 1262 Trout Creek, MT 59874