Logging output in shell scripts is crucial for monitoring, debugging, and maintaining scripts effectively. By capturing important events, errors, and informational messages, developers can trace the execution flow and identify issues. Here are three diverse, practical examples that showcase how to implement logging in shell scripts.
This example demonstrates how to log messages to a specific log file. This is useful in scripts that perform repetitive tasks, allowing you to keep track of execution details over time.
#!/bin/bash
LOGFILE="script.log"
## Function to log messages
log_message() {
echo "
\((date '+%Y-%m-%d %H:%M:%S') - \)1" >> "$LOGFILE"
}
## Main script execution
log_message "Script started"
## Simulating some operations
for i in {1..5}; do
log_message "Processing item $i"
sleep 1 # Simulate a task
log_message "Completed item $i"
done
log_message "Script ended"
log_message
function formats log entries with a timestamp and appends them to the specified log file.LOGFILE
variable.In this example, we’ll log error messages when a command fails. This is particularly useful for scripts that perform critical tasks, ensuring that failures are documented for later review.
#!/bin/bash
LOGFILE="error.log"
## Function to log error messages
log_error() {
echo "
\((date '+%Y-%m-%d %H:%M:%S') - ERROR: \)1" >> "$LOGFILE"
}
## A sample command that might fail
command_to_run() {
# # Simulating a command that fails
false
}
## Main script execution
echo "Starting command..."
if ! command_to_run; then
log_error "Command failed"
fi
echo "Script completed"
if !
, logging an error message if the command fails.This example introduces dynamic log levels, allowing users to control the verbosity of the logging output. This can be particularly useful in larger scripts where you may want detailed logs during development and minimal logs in production.
#!/bin/bash
LOGFILE="dynamic.log"
LOG_LEVEL="INFO"
## Function to log messages based on log level
log_message() {
local level="$1"
shift
if [[ "\(level" == "DEBUG" && "\)LOG_LEVEL" == "DEBUG" ]] || [[ "\(level" == "INFO" ]] || [[ "\)level" == "ERROR" ]]; then
echo "
\((date '+%Y-%m-%d %H:%M:%S') - \)level: \(@" >> "\)LOGFILE"
fi
}
## Main script execution
log_message "INFO" "Starting script"
log_message "DEBUG" "This is a debug message"
log_message "INFO" "Performing an important task"
## Simulating task completion
if true; then
log_message "INFO" "Task completed successfully"
else
log_message "ERROR" "Task failed"
fi
log_message "INFO" "Ending script"
LOG_LEVEL
variable to control the output. Set it to DEBUG
for detailed logs.log_message
to manage log levels as per your needs, allowing for more granular control over logging output.