When a command ends, it hands the shell a number: its exit code. 0 means it worked. Any other number means it failed.
$? holds the last one:
text
learner@reef:~$ grep -q tea menu.txt
learner@reef:~$ echo $?
0 ← found
learner@reef:~$ grep -q juice menu.txt
learner@reef:~$ echo $?
1 ← not found
learner@reef:~$ cta menu.txt
bash: cta: command not found
learner@reef:~$ echo $?
127
learner@reef:~$ echo $?
0 ← the code of the echo abovegrep -q prints nothing: its exit code is its answer. $? changes after every command, echo too.
| Code | Means |
|---|---|
0 | It worked |
1 | It failed: grep found no line |
2 | Used wrongly, or a file it was given isn't there |
126 | Found, but can't run: a file without x |
127 | Command not found: a typo |
A script's exit code
A script ends with the code of its last command. ~/on-menu.sh:
bash
#!/bin/bash
# Usage: on-menu.sh WORD
grep -q "$1" ~/menu.txttext
learner@reef:~$ ./on-menu.sh cake; echo $? ← ; runs one command, then the next
0
learner@reef:~$ ./on-menu.sh pie; echo $?
1exit N ends a script at once with the code N, like chapter 1's exit 1. The next page puts these codes to work.