When a command ends, it gives a number to the shell: its exit code. The exit code tells you if the command worked.
| Exit code | Means |
|---|---|
0 | Success |
| Any other number, 1 to 255 | A problem. The number says which kind |
There is one code for success and many codes for problems.
$?: the last exit code
$? holds the exit code of the last command:
text
learner@tidepool:~$ grep tea menu.txt
tea 4.50
learner@tidepool:~$ echo $?
0
learner@tidepool:~$ grep juice menu.txt
learner@tidepool:~$ echo $?
1$? changes after every command, also after echo. Read it at once.
Codes that you will see often
| Code | Means |
|---|---|
0 | Success |
1 | A general problem. For grep: no line matched |
2 | Wrong use, such as a file that does not exist for ls |
126 | The file exists but cannot run (Permission denied) |
127 | command not found |
A script sets its own code
A script ends with the exit code of its last command. exit N ends it at once, with the code N:
text
#!/bin/bash
grep -q ERROR ~/logs/till.log
exit 3Programs that run other programs, for example to check a new release, use the exit code: 0 passes, anything else fails.