Exit Status ($?) in Shell Script

Exit Status ($?) in Shell Script

#devops #linux #shell-scripting

Exit Status

  • Every command returns an exit status (sometimes referred to as a return status or exit code).

  • A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

  • Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.

  • When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the last command executed in the script (previous to the exit).

How to find out the exit code of a command?

You need to use a particular shell variable called $? to get the exit status of the previously executed command.

┌──(ubuntu@ec2-13-232-90-141)-[~]
└─$ echo "Learning-Ocean"
Learning-Ocean

┌──(ubuntu@ec2-13-232-90-141)-[~]
└─$ echo "echo: Command Not Found"
echo: Command Not Found

┌──(ubuntu@ec2-13-232-90-141)-[~]
└─$ echo $?
0 # getting exit status is zero means last command executed successfully.

┌──(ubuntu@ec2-13-232-90-141)-[~]
└─$ hello
hello: command not found

┌──(ubuntu@learning-ocean)-[~]
└─$ echo $?
197 # getting exit status as non zero means last command not executed successfully.