0
0
Bash Scriptingscripting~20 mins

Error logging patterns in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Logging Patterns in Bash Scripts
📖 Scenario: You are writing a simple bash script to run commands and log any errors that happen during execution. Proper error logging helps you find and fix problems quickly.
🎯 Goal: Build a bash script that runs a command, captures errors, and writes error messages to a log file with timestamps.
📋 What You'll Learn
Create a variable to hold the log file path
Create a function to log errors with timestamps
Run a command and capture any error output
Use the error logging function to write errors to the log file
Print a message indicating if the command succeeded or failed
💡 Why This Matters
🌍 Real World
Error logging is essential in scripts that automate tasks, so you can quickly find and fix problems without manually checking outputs.
💼 Career
DevOps engineers and system administrators use error logging patterns to maintain reliable automation scripts and troubleshoot issues efficiently.
Progress0 / 4 steps
1
Create a log file variable
Create a variable called LOG_FILE and set it to "error.log" to store the error log filename.
Bash Scripting
Need a hint?

Use = to assign the string "error.log" to the variable LOG_FILE.

2
Create an error logging function
Create a function called log_error that takes one argument message. Inside the function, append the current date and time followed by the message to the file stored in LOG_FILE. Use date +"%Y-%m-%d %H:%M:%S" to get the timestamp.
Bash Scripting
Need a hint?

Define the function with log_error() { ... }. Use echo with date and append to $LOG_FILE using >>.

3
Run a command and capture errors
Run the command ls /nonexistent_directory and redirect its error output to a variable called error_output. Use command substitution with $( ... ) and redirect standard error with 2>&1.
Bash Scripting
Need a hint?

Use $(ls /nonexistent_directory 2>&1) to capture error output into error_output.

4
Log errors and print result
Check if error_output is not empty. If it has content, call log_error with error_output as argument and print "Command failed, error logged.". Otherwise, print "Command succeeded.".
Bash Scripting
Need a hint?

Use if [ -n "$error_output" ] to check if the variable is not empty.