To get the exit code of a command in Bash on a Linux or Unix-like system, you can use the $?
special variable. This variable contains the exit code of the last executed command.
Here is an example of how to use the $?
variable to get the exit code of a command:
# Run a command mycommand # Get the exit code of the command exit_code=$? # Print the exit code echo "The exit code of the command was: $exit_code"
In this example, the mycommand
command is run first, and then the $?
variable is used to get its exit code. The exit code is stored in the $exit_code
variable, and then it is printed to the console using the echo
command.
The exit code of a command indicates whether the command was successful or not. In Bash, a successful command will have an exit code of 0, and a failed command will have a non-zero exit code. You can use the $?
variable to check the exit code of a command and take appropriate action based on the result.
Note that the $?
variable will only contain the exit code of the last executed command. If you run multiple commands in a sequence, the $?
variable will only contain the exit code of the last command. Consult the Bash documentation for more information about the $?
variable and exit codes in Bash.