Bird
Raised Fist0
Bash Scriptingscripting~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the exit code 0 usually mean in bash scripting?
easy
A. The command is still running
B. The command failed
C. The command was skipped
D. The command was successful

Solution

  1. Step 1: Understand exit codes meaning

    In bash, exit code 0 means success, any other number means failure or error.
  2. Step 2: Interpret exit code 0

    Since 0 means success, the command completed without errors.
  3. Final Answer:

    The command was successful -> Option D
  4. Quick Check:

    Exit code 0 = success [OK]
Hint: Exit code 0 means success, anything else means error [OK]
Common Mistakes:
  • Thinking 0 means failure
  • Confusing exit code with process ID
  • Checking $? too late after command
2. Which of the following is the correct way to check the exit code of the last command in bash?
easy
A. echo $exit_code
B. echo $?
C. echo $lastcode
D. echo $status

Solution

  1. Step 1: Recall special variable for exit code

    The special variable $? holds the exit code of the last command.
  2. Step 2: Verify correct syntax

    Using echo $? prints the exit code correctly.
  3. Final Answer:

    echo $? -> Option B
  4. Quick Check:

    Use $? to get last exit code [OK]
Hint: Use $? immediately after command to get exit code [OK]
Common Mistakes:
  • Using undefined variables like $exit_code
  • Forgetting to check $? right after command
  • Using $status which is not standard
3. What will be the output of this script?
ls /nonexistent_dir
 echo $?
medium
A. 2
B. 0
C. No output
D. ls: cannot access '/nonexistent_dir': No such file or directory

Solution

  1. Step 1: Understand the command behavior

    The command ls /nonexistent_dir tries to list a folder that does not exist, so it fails.
  2. Step 2: Check exit code after failure

    After failure, $? holds a non-zero exit code, 2 for ls missing directories.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Failed command exit code ≠ 0 [OK]
Hint: Failed commands return non-zero exit codes like 2 [OK]
Common Mistakes:
  • Assuming output is 0 for failure
  • Confusing error message with exit code
  • Expecting no output from echo
4. Consider this script snippet:
mkdir test_dir
false
if [ $? -eq 0 ]; then
  echo "Created"
else
  echo "Failed"
fi

What is the problem if the script always prints "Failed" even when the directory is created?
medium
A. mkdir command does not set exit code
B. The syntax of if statement is wrong
C. The $? is checked too late after mkdir
D. echo command overwrites the exit code

Solution

  1. Step 1: Understand exit code timing

    The exit code $? must be checked immediately after the command it relates to.
  2. Step 2: Identify delay in checking exit code

    If any command runs between mkdir and checking $?, the exit code changes.
  3. Final Answer:

    The $? is checked too late after mkdir -> Option C
  4. Quick Check:

    Check $? immediately after command [OK]
Hint: Check $? right after command, no commands in between [OK]
Common Mistakes:
  • Checking $? after other commands
  • Assuming mkdir never fails
  • Misunderstanding if syntax
5. You want to run two commands in a script: cmd1 and cmd2. You want to run cmd2 only if cmd1 succeeded (exit code 0). Which is the best way to do this?
hard
A. cmd1 && cmd2
B. cmd1 || cmd2
C. cmd1; if [ $status -eq 0 ]; then cmd2; fi
D. if [ cmd1 ]; then cmd2; fi

Solution

  1. Step 1: Understand conditional execution operators

    The operator && runs the second command only if the first succeeds (exit code 0).
  2. Step 2: Compare options for best practice

    cmd1 && cmd2 uses cmd1 && cmd2 which is concise and reliable for this purpose.
  3. Final Answer:

    cmd1 && cmd2 -> Option A
  4. Quick Check:

    Use && to run second command only if first succeeds [OK]
Hint: Use && to run next command only if previous succeeds [OK]
Common Mistakes:
  • Using || which runs second if first fails
  • Checking $? manually when && is simpler
  • Using if with command but less concise
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard