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

  1. 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.
  2. Run a simple command. Type a standard command and press Enter. For this guide, we will use the ls command, which lists the files in your current directory. Type ls and press Enter. Note that this command usually returns a list of filenames.
  3. 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 like ls, it will almost always return 0. If you see a number other than 0, the command failed.
  4. 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".
  5. 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.
  6. Understand the number. While any non-zero number means failure, specific numbers often have standard meanings. For ls, a return of 0 means success. A return of 1 often indicates a general error, while 2 often 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.
  7. Use exit codes in a script. Create a new text file named check_status.sh (or check_status.bat on Windows). This file will contain a script that performs a task and then checks the code. For a script, you would use an if statement 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 runs ls, then checks the exit code. If the code is 0, it prints "Success"; otherwise, it does nothing.
  8. 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 named exit.log. You can then open exit.log with a text editor to see the number.
  9. Inspect the saved file. Open the exit.log file 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.
  10. 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 1 always means "permission denied" and 2 always 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 if statements 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 -e for automatic error handling. In shell scripts, you can add the line set -e at 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 -u for undefined variable handling. You can also use set -u to 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 pipefail for pipeline error handling. By default, the exit code of a pipeline is the exit code of the last command. With set -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 10 for a file not found error and 20 for a permission denied error. This makes it easier to handle different types of errors in your scripts.
  • Use man to find codes. If you are unsure what an exit code means, use the man command to look up the manual for the specific command. For example, man ls will show you the exit codes for the ls command.

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 is ls. 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 ping command returns 0 if it gets a response, but returns 1 if it does not. The grep command 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.log works, but the syntax exit.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 -e line at the top of your script. If you are using set -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 || true at 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.