Bash get exit code of command on a Linux / Unix

In Bash, the exit code of a command can be accessed using the special variable $?. The exit code is a numeric value that represents the status of the command’s execution. A value of 0 typically indicates success, while a non-zero value indicates failure.

Here is an example of how to check the exit code of a command:

command
echo "Exit code: $?"

You can also use command substitution to assign the exit code to a variable:

result=$(command)
echo "Exit code: $?"

You can also use && operator to execute a command only if the previous command was successful.

command1 && command2

You can also use || operator to execute a command only if the previous command was unsuccessful.

command1 || command2

In addition, you can use if statement to check the exit code and take different actions based on the result:

if command; then
echo "Command succeeded"
else
echo "Command failed"
fi

Note: These are just general examples, for more detailed and accurate steps please refer to the official documentation of Bash and Linux/Unix.

Leave a Comment