0
0
Bash Scriptingscripting~5 mins

Error logging patterns in Bash Scripting

Choose your learning style9 modes available
Introduction

Error logging helps you find and fix problems in your scripts by saving error messages in a file or showing them clearly.

When you want to keep track of errors in a script running on a server.
When debugging a script that sometimes fails without clear messages.
When running automated tasks and you need to check what went wrong later.
When you want to separate normal output from error messages.
When you want to alert someone by logging errors to a file.
Syntax
Bash Scripting
command 2> error.log
command >> output.log 2>> error.log
command 2>&1 | tee error.log

2> redirects error messages (stderr) to a file.

>> appends output to a file without overwriting it.

Examples
This runs ls on a missing folder and saves the error message to error.log.
Bash Scripting
ls /not_exist 2> error.log
This appends normal output to output.log and errors to error.log.
Bash Scripting
echo "Hello" >> output.log 2>> error.log
This sends both output and errors to the screen and saves them in error.log.
Bash Scripting
grep 'pattern' file.txt 2>&1 | tee error.log
Sample Program

This script tries to create a directory and list it, logging errors to error.log. It also tries to list a missing directory to generate an error. Finally, it shows the error log content.

Bash Scripting
#!/bin/bash

mkdir /tmp/testdir 2> error.log
ls /tmp/testdir > output.log 2>> error.log
ls /not_exist 2>> error.log

cat error.log
OutputSuccess
Important Notes

Always use 2> to capture errors separately from normal output.

Appending errors with 2>> keeps old logs safe.

Use 2>&1 to combine errors and output if needed.

Summary

Error logging saves error messages for later review.

Use 2> to redirect errors to a file.

Separate normal output and errors for clearer logs.