0
0
Bash Scriptingscripting~5 mins

Error logging patterns in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of error logging in bash scripts?
Error logging helps capture and record errors during script execution. It makes troubleshooting easier by showing what went wrong and where.
Click to reveal answer
beginner
How do you redirect error messages to a log file in bash?
Use the syntax command > logfile 2>&1. This sends both standard output and error output to the log file.
Click to reveal answer
intermediate
What does 2>&1 mean in bash redirection?
It means redirect standard error (file descriptor 2) to the same place as standard output (file descriptor 1).
Click to reveal answer
intermediate
Why use a function for error logging in bash scripts?
A function centralizes error handling. It makes the script cleaner and easier to maintain by reusing the same logging format and actions.
Click to reveal answer
intermediate
Show a simple bash function that logs errors with timestamps.
Example:
log_error() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') ERROR: $1" >&2
}
This prints the error message with a timestamp to standard error.
Click to reveal answer
Which bash redirection sends both output and errors to the same file?
Acommand > logfile 2>&1
Bcommand 2> logfile
Ccommand > logfile
Dcommand 1> logfile 1>&2
What does the following bash code do? exec 2>error.log
ARedirects standard output to error.log
BRedirects all future error messages to error.log
CDeletes error.log
DRuns error.log as a command
Why is it helpful to include timestamps in error logs?
ATo confuse users
BTo make logs bigger
CTo speed up the script
DTo know when errors happened
Which of these is a good practice for error logging in bash scripts?
ALogging errors with clear messages and timestamps
BIgnoring errors silently
CPrinting errors only to the screen without saving
DUsing random file names for logs
What does this function do?
log_error() {
  echo "ERROR: $1" >&2
}
ADeletes error messages
BPrints an error message to standard output
CPrints an error message to standard error
DLogs errors to a file automatically
Explain how to redirect error messages to a log file in a bash script and why it is useful.
Think about how to capture errors and save them for later review.
You got /4 concepts.
    Describe how you would create a reusable error logging function in bash and what features it should have.
    Consider how to make error messages clear and easy to find.
    You got /4 concepts.