Linux bash exit status and how to set exit status in bash

Linux bash exit status and how to set exit status in bash

In Linux, the exit status of a command is a numerical value that indicates the success or failure of the command. The exit status is usually returned to the shell after the command has completed execution.

The exit status is typically represented by a value of 0 for success and a non-zero value for failure. Some common exit status codes and their meanings are:

  • 0: Success
  • 1: General error
  • 2: Misuse of shell builtins
  • 126: Cannot execute the specified command
  • 127: Command not found
  • 128: Invalid argument to exit

In a bash script, you can use the exit command to set the exit status of the script. For example:

refer to‮tual:‬turi.com
# Set the exit status to 1 if the command fails
command || exit 1

# Set the exit status to 0 if the command succeeds
command && exit 0

# Set the exit status to a specific value
exit 123

You can also use the $? variable to retrieve the exit status of the last command. For example:

# Run a command and store its exit status in a variable
status=$?

# Check the exit status
if [ $status -eq 0 ]; then
  echo "Command succeeded"
else
  echo "Command failed with exit status $status"
fi

The exit status is useful for determining the success or failure of a command or script in a shell script. It can also be used to communicate the status of a script to the calling process.

Created Time:2017-10-29 22:09:00  Author:lautturi