0
0
Bash Scriptingscripting~10 mins

Exit codes ($?) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Exit codes ($?)
Run Command
Command Finishes
Shell Stores Exit Code in $?
Check $? for Success (0) or Failure (non-0)
Use Exit Code to Decide Next Steps
When a command runs, the shell saves its exit code in $? which tells if it succeeded (0) or failed (non-zero). You can check $? to decide what to do next.
Execution Sample
Bash Scripting
ls /tmp
 echo $?
false
 echo $?
Run 'ls /tmp' and print its exit code, then run 'false' command and print its exit code.
Execution Table
StepCommand RunExit Code ($?)MeaningAction
1ls /tmp0Success - command found and listed /tmpStore 0 in $?
2echo $?0Prints last exit code (0)Output: 0
3false1Failure - false always returns 1Store 1 in $?
4echo $?1Prints last exit code (1)Output: 1
💡 After each command, $? stores that command's exit code; 0 means success, non-zero means failure.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
$?undefined011
Key Moments - 3 Insights
Why does $? change after each command?
Because $? always holds the exit code of the last command run, as shown in execution_table rows 1 and 3.
What does an exit code of 0 mean?
It means the command succeeded without errors, as seen in execution_table row 1 where ls /tmp returns 0.
Why does the 'false' command return 1?
'false' is a command that always fails and returns exit code 1, shown in execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $? after running 'ls /tmp'?
A0
B1
Cundefined
Dls /tmp
💡 Hint
Check the 'Exit Code ($?)' column in row 1 of the execution_table.
At which step does $? become 1?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Exit Code ($?)' column and find when it changes to 1.
If the command 'true' was run instead of 'false', what would $? be after that command?
A2
B0
C1
Dundefined
💡 Hint
'true' always returns exit code 0, similar to 'ls /tmp' in the table.
Concept Snapshot
Exit codes ($?) in bash store the result of the last command.
0 means success, non-zero means failure.
Check $? immediately after a command to know if it worked.
Use $? in scripts to control flow based on success or failure.
Full Transcript
When you run a command in bash, it finishes and returns an exit code. This code is saved in the special variable $?. A value of 0 means the command succeeded without errors. Any other number means something went wrong. For example, 'ls /tmp' usually succeeds and sets $? to 0. The 'false' command always fails and sets $? to 1. You can check $? right after a command to decide what to do next in your script or terminal session.