0
0
Bash Scriptingscripting~20 mins

Exit codes ($?) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Exit Code Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:00remaining
What is the exit code after a successful command?
Consider the following Bash commands run in sequence:
echo "Hello World"
echo $?
What will be the output of the second echo command?
Bash Scripting
echo "Hello World"
echo $?
A1
B0
CHello World
DCommand not found
Attempts:
2 left
💡 Hint
The exit code $? shows if the last command succeeded or failed. Zero means success.
💻 Command Output
intermediate
1:00remaining
Exit code after a failing command
What will be the output of this script?
ls /nonexistent_directory
echo $?
Bash Scripting
ls /nonexistent_directory
echo $?
ANo such file or directory
B1
C2
D0
Attempts:
2 left
💡 Hint
When a command fails, the exit code is non-zero. Different commands may use different codes.
📝 Syntax
advanced
1:30remaining
Which script correctly checks the exit code?
You want to run a command and then check if it succeeded using its exit code. Which script snippet correctly does this?
A
command
if $? == 0 then
 echo "Success"
fi
B
command
if [ $? -eq 0 ] then
 echo "Success"
fi
C
command
if [$? -eq 0]; then
 echo "Success"
fi
D
command
if [ $? -eq 0 ]; then
echo "Success"
fi
Attempts:
2 left
💡 Hint
Remember to have spaces around brackets and use correct syntax for if statements in Bash.
🚀 Application
advanced
1:30remaining
What is the exit code after a pipeline?
Consider this pipeline:
grep 'pattern' file.txt | sort
echo $?
What does the exit code represent?
Bash Scripting
grep 'pattern' file.txt | sort
echo $?
AExit code of the last command in the pipeline (sort)
BExit code of the first command in the pipeline (grep)
C0 if both commands succeed, else non-zero
DSum of exit codes of both commands
Attempts:
2 left
💡 Hint
In Bash, $? after a pipeline returns the exit code of the last command by default.
🧠 Conceptual
expert
2:00remaining
How to get exit codes of all commands in a pipeline?
You run a pipeline of commands in Bash:
cmd1 | cmd2 | cmd3

How can you get the exit codes of all three commands?
AUse the array ${PIPESTATUS[@]} immediately after the pipeline
BUse the command 'exitcodes' after the pipeline
CUse $? three times, once after each command
DUse 'echo $PIPESTATUS' after the pipeline
Attempts:
2 left
💡 Hint
Bash stores exit codes of all pipeline commands in a special array variable.