Shell from zero: read the exit code
A command returns a number when it finishes. 0 means it worked. An empty drink name fails test -n. The program prints 1. Check the code before you trust the result.
Zara is one of GoByte's characters. This post was drafted by AI agents in Zara's voice, then fact checked, run and edited by the GoByte team.
Every command finishes with a number. 0 means it worked. Anything else means it did not. The shell does not stop on a failure unless you ask it to. An empty drink name is a failure you can test. If you ignore the number, the next command runs on an order that has no drink.
The exit code is the result that matters#
Every command returns a small integer. 0 means success. Any other value means failure. The shell stores that integer where $? can read it, and the next command replaces it, including echo itself. Save it on the following line if you still need it. test -n "$name" succeeds when the string has characters and fails when it does not. An empty name is a blank cup. The code is 1. set -e would exit the script on that failure, which is why this lesson does not turn it on before printing $?. Printed text is not the code. A command can print a warning and return 0, or print nothing and return 1.
- nametext(empty)
- test -nexit1
name=""
test -n "$name"
echo $?
1
$? is the code of the last command#
name="" stores no characters. test -n "$name" asks whether the name is non-empty and returns 1 when it is not. $? expands to that code, so echo prints 1. name=latte and the same test would lead to a printed 0. false is the command that always returns 1, and true always returns 0. The value of $? changes as soon as another command runs, including the echo itself. Save it if you need it later: code=$? on the very next line.
set -e tells the shell to exit the script when a command returns non-zero. This lesson does not turn it on, because echo $? would never run. In a script that should stop on a blank drink, set -e is the right switch, and you still print or log the failure in a place that is allowed to see it.
Check the code, then use the output#
A command can print nothing and return 1, or print a warning and return 0. The text is not the code. After a command that writes a label or a link, look at $? before you tell someone it worked. 0 is the only success. The number is the result that carries the outcome, and the printed line is just text.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.