Yes, you can check the result of a command by using the special variable $? in the shell, or redirecting the status to a file (like command arg1 arg2; echo $? > exit.log) to inspect it later. Exit codes are small numbers used by the operating system to tell you if a command succeeded (zero) or failed (non-zero). They are the primary way automation scripts, cron jobs, and shell pipelines determine whether to proceed with the next step or report an error. Understanding them allows you to write robust scripts that react intelligently to errors rather than failing blindly.
What You'll Need
- A computer with a command line interface (Terminal on macOS or Linux, Command Prompt or PowerShell on Windows).
- A basic text editor (like Notepad, TextEdit, or Nano) to create a script file.
- A command to test, such as
ls(list directory),ping, or a custom script.
Step-by-Step
- Open your terminal or command prompt. You can usually do this by pressing the Windows key, typing "Terminal" or "Command Prompt", and selecting it. On macOS, open the "Utilities" folder inside "Applications" and launch "Terminal". On Linux, it is often available in the application menu.
- Run a simple command. Type a standard command and press Enter. For this guide, we will use the
lscommand, which lists the files in your current directory. Typelsand press Enter. Note that this command usually returns a list of filenames. - Check the exit code immediately. Type the special variable
$?and press Enter immediately after running the command. The $? variable holds the exit status of the last command executed. For a successful command likels, it will almost always return0. If you see a number other than 0, the command failed. - Test a failing command. Now, run a command that is known to fail. A common example on Unix-like systems is
ls /nonexistentdirectory, which tries to list a folder that doesn't exist. You will likely see an error message, such as "No such file or directory". - Check the exit code again. Immediately after the error message, type
$?and press Enter. You will see a non-zero number (often 2). This number is the exit code, indicating that the operation failed. - Understand the number. While any non-zero number means failure, specific numbers often have standard meanings. For
ls, a return of0means success. A return of1often indicates a general error, while2often indicates a specific file or argument error. However, different commands can use different codes, so checking the manual (man ls) is the most reliable way to know. - Use exit codes in a script. Create a new text file named
check_status.sh(orcheck_status.baton Windows). This file will contain a script that performs a task and then checks the code. For a script, you would use anifstatement to check the value of$?. For example, to run a command and only print "Success" if it worked, you would write:ls /some/directory; if [ $? -eq 0 ]; then echo "Success"; fi. This command first runsls, then checks the exit code. If the code is 0, it prints "Success"; otherwise, it does nothing. - Redirect the exit code to a file. If you want to save the exit code for later analysis, you can redirect the special variable to a file. Type the following command into your terminal:
ls /nonexistentdirectory; echo $? > exit.log. This runs the failing command, then saves the exit code to a file namedexit.log. You can then openexit.logwith a text editor to see the number. - Inspect the saved file. Open the
exit.logfile you just created. It will contain the exit code, typically a non-zero number like 2. This demonstrates how you can log errors from long-running processes or background jobs. - Use exit codes in pipelines. Exit codes are particularly useful in pipelines, where the output of one command feeds into another. The exit code of the entire pipeline is the exit code of the last command in the chain. For example,
ls | grep "missingfile" | echo "Found it". If the grep command fails to find a match, it will return a non-zero code, and the echo command will not run.
Common Mistakes
- Forgetting to check immediately. A common mistake is to run a command and then perform many other actions before checking
$?. The variable is overwritten every time a new command is run. Always check$?right after the command that produced the result. - Assuming a number means a specific error. Many users assume that
1always means "permission denied" and2always means "file not found." While these are common, they are not universal. Different commands can use the same numbers for different purposes. Always refer to the command's manual page for the specific meanings of its exit codes. - Ignoring the exit code in scripts. Writing scripts that ignore exit codes is a recipe for bugs. If a script runs a command for file processing and the file is missing, but the script continues to the next step, it can produce confusing or corrupt results. Always use
ifstatements to check the code and handle errors appropriately. - Writing complex logic in the shell. While you can write complex scripts using only exit codes, it is often cleaner to handle errors in the script itself, before passing data to the command. For example, check if a file exists before trying to list it. This makes the script easier to read and debug.
Tips
- Use
set -efor automatic error handling. In shell scripts, you can add the lineset -eat the very top. This tells the shell to exit immediately if any command returns a non-zero exit code. This is a powerful way to prevent scripts from continuing after an error. - Use
set -ufor undefined variable handling. You can also useset -uto tell the shell to exit if you try to use a variable that hasn't been set. This can help you catch typos in variable names early. - Use
set -o pipefailfor pipeline error handling. By default, the exit code of a pipeline is the exit code of the last command. Withset -o pipefail, the exit code of the pipeline is the exit code of the first command to fail. This makes it easier to debug pipeline errors. - Use custom exit codes. In your own scripts, you can return custom exit codes to indicate specific types of errors. For example, you could return
10for a file not found error and20for a permission denied error. This makes it easier to handle different types of errors in your scripts. - Use
manto find codes. If you are unsure what an exit code means, use themancommand to look up the manual for the specific command. For example,man lswill show you the exit codes for thelscommand.
Troubleshooting
- The exit code is always 0, but the command failed. This can happen if you are running a command that returns a non-zero code, but then immediately overwriting it with another command's result. For example, if you run
ls; echo $?; ls, the$?will always be 0 because the last command isls. Always check the code immediately after the command you want to test. - The exit code is different than expected. As mentioned, different commands can use different exit codes. For example, the
pingcommand returns 0 if it gets a response, but returns 1 if it does not. Thegrepcommand returns 0 if it finds a match, but returns 1 if it does not. Always check the manual for the specific command you are using. - Exit codes are not being saved correctly. If you are redirecting the exit code to a file, make sure you are using the correct syntax. The syntax
echo $? > exit.logworks, but the syntaxexit.log < echo $?will not work. The redirection operator (>) must come before the file name. - Script continues after an error. If your script is not exiting when it should, check if you have the
set -eline at the top of your script. If you are usingset -e, make sure you are not running a command that returns a non-zero code intentionally. For example, if you want to ignore an error, you can run the command with a|| trueat the end. This will force the exit code to be 0, even if the command failed. - Exit codes are not working in PowerShell. In PowerShell, the equivalent of
$?is the automatic variable$LASTEXITCODE. The variable$?in PowerShell returns a boolean indicating whether the last command succeeded, but it does not hold the actual exit code. To get the exit code, you must use$LASTEXITCODE.
Frequently Asked Questions
What does an exit code of 0 mean?
An exit code of 0 means that the command executed successfully and completed without any errors. This is the standard success code used by most operating systems and shell commands.
Why do exit codes matter?
Exit codes are crucial for automation and scripting. They allow scripts to make decisions based on the success or failure of previous commands. For example, a backup script might only email an administrator if the backup process itself failed.
What is the difference between $? and $LASTEXITCODE?
In Unix-like shells (Bash, Zsh), $? holds the exit code of the last command. In PowerShell, $LASTEXITCODE holds the exit code of the last external command, while $? is a boolean indicating success or failure.
Can I define my own exit codes?
Yes, you can define your own exit codes in your own scripts. You can return any non-zero number to indicate a specific type of error. This can help you handle different types of errors in your scripts.
How do I make a script exit on the first error?
You can use the set -e command at the beginning of your script. This tells the shell to exit immediately if any command returns a non-zero exit code. You can also use set -u to exit if you try to use an undefined variable.
Are exit codes standardized?
While some numbers like 0 and 1 are standard, there is no universal standard for all exit codes. Different commands and different operating systems can use different numbers for different purposes. Always refer to the manual for the specific command you are using.