Jake Worth

Print Last Exit Code

Published: October 21, 2022 2 min read

The exit code of a command in a Unix-based system is an important and easy-to-miss piece of data. It isn’t printed to standard out; you have to go looking for it. I find it useful to inspect this information when debugging or considering chaining unfamiliar commands.

To see the exit code of your last command, echo its variable ($) value:

$ echo "something"
"something"
$ echo $?
0 # Success!
# '1' example
$ rm nonexistent-file
rm: nonexistent-file: No such file or directory
$ echo $?
1 # Failure.

The two exit codes you must remember are 0, command was successful, and 1, a catch-all for errors. Zero is success, not-zero failure.

I have a terminal function that prints this variable:

# Print the last exit status
function print_status() {
  echo $?
}

✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!


Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.