0
0
Bash Scriptingscripting~5 mins

Custom exit codes (exit N) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does exit N do in a bash script?

exit N stops the script and sends the number N as the exit code to the system. This code tells if the script ended successfully or with an error.

Click to reveal answer
beginner
Why use custom exit codes instead of just exit 0 or exit 1?
<p>Custom exit codes let you show different reasons for failure or success. For example, <code>exit 2</code> might mean "file not found," while <code>exit 3</code> means "permission denied." This helps other scripts or users understand what happened.</p>
Click to reveal answer
beginner
What is the valid range for exit codes in bash scripts?

Exit codes must be between 0 and 255. 0 means success, and any number from 1 to 255 means different errors or statuses.

Click to reveal answer
beginner
How can you check the exit code of the last command in bash?

Use the special variable $?. It holds the exit code of the last command or script run.

Click to reveal answer
beginner
Example: What exit code will this script return?<br>
#!/bin/bash
if [ ! -f myfile.txt ]; then
  exit 2
else
  exit 0
fi

If myfile.txt does not exist, the script exits with code 2. Otherwise, it exits with 0 meaning success.

Click to reveal answer
What does exit 0 usually mean in a bash script?
AThe script ran successfully
BThe script failed
CThe script is still running
DThe script has a syntax error
Which exit code range is valid in bash scripts?
AAny positive number
B1 to 100
C0 to 1000
D0 to 255
How do you get the exit code of the last command in bash?
A$!
B$?
C$#
D$$
If a script ends with exit 3, what does it mean?
AThe script succeeded
BThe script is running in background
CThe script failed with a specific error
DThe script is paused
What happens if you use exit 300 in a bash script?
AIt exits with code 44 (300 modulo 256)
BIt exits with code 300
CIt causes an error and script stops immediately
DIt exits with code 0
Explain how and why you would use custom exit codes in a bash script.
Think about how scripts tell the system if they succeeded or failed.
You got /4 concepts.
    Describe how to check the exit code of the last command and why it is useful.
    This is how you know if a command worked before moving on.
    You got /4 concepts.