Exit Codes
Success or failure.
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.

- 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.
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.
| key | value |
|---|---|
| 0 | success |
| 1 | general error |
| 2 | missing file, misuse |
| 127 | command 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