Challenge - 5 Problems
Error Handling Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
π» Command Output
intermediate2:00remaining
What is the output when a command fails without error handling?
Consider this bash script snippet:
What will be the output when run as a normal user without root privileges?
#!/bin/bash mkdir /root/testdir echo "Directory created"
What will be the output when run as a normal user without root privileges?
Bash Scripting
#!/bin/bash mkdir /root/testdir echo "Directory created"
Attempts:
2 left
π‘ Hint
Think about what happens when mkdir fails but the script continues.
β Incorrect
Without error handling, the mkdir command fails and prints an error to stderr, but the script continues and prints 'Directory created'. This can mislead users into thinking the directory was created successfully.
π§ Conceptual
intermediate1:30remaining
Why use 'set -e' in bash scripts?
What is the main effect of adding
set -e at the start of a bash script?Attempts:
2 left
π‘ Hint
Think about how to stop a script when something goes wrong.
β Incorrect
set -e causes the script to stop running as soon as any command fails, preventing silent failures and unexpected behavior.π§ Debug
advanced2:30remaining
Identify the error handling problem in this script
What is wrong with the error handling in this bash script?
#!/bin/bash cp /source/file.txt /dest/ if [ $? -eq 0 ]; then echo "Copy succeeded" else echo "Copy failed" fi rm /source/file.txt
Bash Scripting
#!/bin/bash cp /source/file.txt /dest/ if [ $? -eq 0 ]; then echo "Copy succeeded" else echo "Copy failed" fi rm /source/file.txt
Attempts:
2 left
π‘ Hint
Look at what happens after the copy command regardless of success.
β Incorrect
The script removes the source file even if the copy failed, which can cause data loss. Proper error handling should prevent deleting the source if the copy did not succeed.
π Application
advanced2:30remaining
How to handle errors in a pipeline to avoid silent failures?
Given this pipeline:
Which approach ensures the script detects if any command in the pipeline fails?
cat file.txt | grep 'pattern' | sort > output.txt
Which approach ensures the script detects if any command in the pipeline fails?
Attempts:
2 left
π‘ Hint
By default, bash only returns the last command's status in a pipeline.
β Incorrect
set -o pipefail makes the pipeline return a failure status if any command fails, preventing silent failures in pipelines.π§ Conceptual
expert3:00remaining
Why is explicit error handling better than ignoring errors in automation scripts?
In automation scripts, why is it important to handle errors explicitly rather than ignoring them?
Attempts:
2 left
π‘ Hint
Think about what happens if a script continues after a failure unnoticed.
β Incorrect
Handling errors explicitly ensures the script stops or reacts properly when something goes wrong, avoiding bigger issues later and making debugging easier.