0
0
Bash Scriptingscripting~10 mins

Why error handling prevents silent failures in Bash Scripting - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to stop the script if a command fails.

Bash Scripting
set [1]
Drag options to blanks, or click blank then click option'
A-x
B-e
C-u
D-v
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'set -x' which only prints commands but doesn't stop on errors.
Forgetting to use any option, so errors are ignored.
2fill in blank
medium

Complete the code to check if the last command failed and print an error message.

Bash Scripting
if [[ [1] -ne 0 ]]; then echo "Error occurred"; fi
Drag options to blanks, or click blank then click option'
A$!
B$#
C$?
D$$
Attempts:
3 left
💡 Hint
Common Mistakes
Using '$#' which counts script arguments, not exit status.
Using '$$' which is the process ID, not exit status.
3fill in blank
hard

Fix the error in the code to correctly handle command failure.

Bash Scripting
command_that_might_fail
if [ [1] ]; then echo "Failed"; fi
Drag options to blanks, or click blank then click option'
A$? -ne 0
B$? == 0
C$? == 1
D$? -eq 0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for success instead of failure.
Using '==' inside single brackets which is invalid.
4fill in blank
hard

Fill both blanks to run a command and exit if it fails.

Bash Scripting
[1] || [2]
Drag options to blanks, or click blank then click option'
Acommand_that_might_fail
Bexit 1
Cecho 'Error detected'
Dcontinue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'continue' which is invalid outside loops.
Not exiting on failure, so errors are ignored.
5fill in blank
hard

Fill all three blanks to create a function that runs a command and handles errors.

Bash Scripting
run_command() {
  [1]
  if [[ [2] -ne 0 ]]; then
    [3]
  fi
}
Drag options to blanks, or click blank then click option'
Acommand "$@"
B$?
Cecho 'Command failed' && exit 1
Dreturn 0
Attempts:
3 left
💡 Hint
Common Mistakes
Not passing arguments to the command.
Not checking exit status properly.
Not exiting on failure.