AI Hints
Home›Linux Tutorial›Exit Codes, diff, xargs
Linux · Lesson 55 of 120

Exit Codes

Success or failure.

⏱ 2 min read▶ Video at 1:10:33🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

How did the two ampersands know whether a command worked? Every command, when it finishes, quietly hands back a number. It's called the exit code, and it says whether things went well.

Exit Codes
From the video: Exit Codes
  • How does && know?
  • Every command returns a number
  • The exit code

Reading the exit code

Dollar question mark holds the exit code of the last command. LS on a file that exists succeeds, and the code is zero. LS on a missing file fails, and the code is two. Grep returns one when it finds no matches.

Terminal
ls notes.txt
notes.txt
echo $?
0
ls missing.txt
ls: cannot access 'missing.txt': No such file or directory
echo $?
2
grep banana notes.txt; echo $?
1

What the numbers mean

Zero always means success. Any other number means something went wrong. And different numbers can mean different problems. One is a general error, two often means a missing file or a misuse, and one hundred and twenty seven means command not found. In scripts, you'll use exit codes to decide what to do next.

keyvalue
0success
1general error
2missing file, misuse
127command not found

Why zero means success

It might feel backwards that zero is good. But think of it this way. There's only one way to succeed, but many ways to fail. So success gets one number, zero, and each kind of failure can have its own number.

Zero

  • Success
  • Only one way to succeed
  • Used by &&

Not zero

  • Failure
  • Many ways to fail
  • Used by ||

Summary

Every command returns an exit code. Zero means success, anything else means failure. Dollar question mark shows the last one. Next, comparing two files with diff.

Key takeaways
  • echo $?
  • 0 = success
  • not 0 = failure
Next up: diff: Comparing Files — what changed?