Bash Logging
Logging is printing short status lines so a reader can follow what a script did. Each line carries a fixed label that names its severity.
Fixed labels mark each log line
Three small functions print one label each. The error line goes to stderr first, then the script shows it from a capture file.
log_info() {
echo "[INFO] $1"
}
log_warn() {
echo "[WARN] $1"
}
log_error() {
echo "[ERROR] $1" >&2
}
log_info "backup started"
log_warn "disk is nearly full"
log_error "backup failed" 2> errors.txt
cat errors.txtErrors go to stderr while progress stays on stdout
The info line prints to stdout as normal. The error line is sent to a file that stands in for stderr, then the file is shown.
log_info() {
echo "[INFO] $1"
}
log_error() {
echo "[ERROR] $1" >&2
}
log_info "backup started"
log_error "disk full" 2> errors.txt
echo "lines captured from stderr:"
cat errors.txtA log function can also keep a copy in a file
Each call prints its line and appends the same line to a file. Reading the file at the end shows both lines in order.
log_info() {
echo "[INFO] $1"
echo "[INFO] $1" >> run.log
}
log_info "backup started"
log_info "backup finished"
echo "log file holds:"
cat run.logExample
#!/bin/bash
log_info() {
echo "[INFO] $1"
echo "[INFO] $1" >> run.log
}
log_warn() {
echo "[WARN] $1"
echo "[WARN] $1" >> run.log
}
log_error() {
echo "[ERROR] $1" >&2
}
log_info "backup started"
log_warn "disk is nearly full"
log_error "copy failed" 2> errors.txt
echo "errors captured from stderr:"
cat errors.txt
echo "log file holds:"
cat run.logKey points
- [INFO]: a label for a normal progress line.
- [WARN]: a label for a problem the script can work around.
- [ERROR]: a label for a failure that needs attention.
- stderr: the stream for errors, kept apart from normal output.
- stdout: the stream for normal results and progress lines.
- Log file: a file that keeps a copy of the log lines.
In this example, three log functions are defined, one per level. Info and warn lines print to stdout and are also saved to a log file. The error line goes to stderr and is captured in a separate file. The script then shows the captured error lines and the log file contents.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where should an [ERROR] line go?