The exit status of a command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Revision as of 20:02, 1 September 2009 by Admin (talk | contribs)
Jump to navigation Jump to search

Each Linux command returns a status when it terminates normally or abnormally. You can use command exit status in the shell script to display an error message or take some sort of action. For example, if tar command is unsuccessful, it returns a code which tells the shell script to send an e-mail to sys admin.

Exit Status

  • Every Linux command executed by the shell script or user, has an exit status.
  • The exit status is an integer number.
  • The Linux man pages stats the exit statuses of each command.
  • 0 exit status means the command was successful without any errors.
  • A non-zero (1-255 values) exit status means command was failure.
  • You can use special shell variable called ? to get previously executed command. To print ? variable use the echo command (echo $?

How Do I See Exit Status Of The Command?

Type the following command:


To view exist status of date command, enter:

echo $?

Sample Output:


Try non-existence command

echo $?
ls /eeteec
echo $?

Sample Output:


According to ls man page - exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.

How Do I Store Exit Status Of The Command In a Shell Variable?

Assign $? to a shell variable:

ls -l /tmp
echo "ls command exit stats - $status"

Exit Status Shell Script Example

A simple shell script to locate username (

# set var 

# get user name
read -p "Enter a user name : " username

# try to locate username in in /etc/passwd
grep "^$username" $PASSWD_FILE > /dev/null

# store exit status of grep
# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts

if test $status -eq 0
	echo "User '$username' found in $PASSWD_FILE file."
	echo "User '$username' not found in $PASSWD_FILE file."

Save and close the file. Run it as follows:

chmod +x

Sample Outputs:

Enter a user name : vivek
User 'vivek' found in /etc/passwd file.

Run it again:

chmod +x

Sample Outputs:

Enter a user name : tommy
User 'tommy' not found in /etc/passwd file.