Shell: How to determine the exit status of Linux and UNIX command

www‮ttual.‬uri.com
Shell: How to determine the exit status of Linux and UNIX command

To determine the exit status of a Linux or UNIX command, you can use the $? special shell variable.

The exit status of a command is a numeric value that indicates the success or failure of the command. A value of 0 indicates success, while a non-zero value indicates an error.

To determine the exit status of a command, you can use the $? variable after running the command:

command
echo $?

For example, to determine the exit status of the ls command:

ls /non-existent-directory
echo $?

This will print the exit status of the ls command to the console. In this case, the ls command will return an error because the /non-existent-directory directory does not exist, so the exit status will be non-zero.

You can use the exit status in scripts and shell commands to perform different actions based on the success or failure of the command.

For example, you can use the if statement to check the exit status and print a message based on the result:

command
if [ $? -eq 0 ]; then
  echo "Command succeeded"
else
  echo "Command failed"
fi

This will print Command succeeded if the command was successful or Command failed if the command returned an error.

Keep in mind that the $? variable only stores the exit status of the last command. If you run multiple commands, the $? variable will only contain the exit status of the last command. You can use other techniques, such as storing the exit status in a variable or using the && and || operators, to manage the exit status of multiple commands.

Created Time:2017-10-30 14:27:18  Author:lautturi