Appending Logs to a File

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 115 of 205

A log file records what a script did and when: which steps ran, what failed, how long it took. Scripts that run unattended, such as cron jobs, backups and deployments, have no one watching the terminal, so the log is often the only way to find out afterwards what happened. In Bash, writing a log means appending lines to a file with the >> redirection operator.

echo "first run" >> app.log
echo "second run" >> app.log
cat app.log
first run
second run

>> opens the file for appending: new text goes after the existing content, and the file is created if it does not exist. Each run of the script adds to the history instead of replacing it.

Why >> and Not >

The single > operator truncates the file to zero length before writing (lesson 57). Using it for a log keeps only the last line written:

echo "oops" > app2.log
echo "again" > app2.log
cat app2.log
again

A one-character typo can therefore wipe out a whole log history. set -o noclobber (lesson 57) makes > refuse to overwrite an existing file, while >> still works:

set -C
echo x >> nc.log
echo y >> nc.log
echo z > nc.log
bash: nc.log: cannot overwrite existing file

nc.log keeps x and y.

Append mode has a second advantage. When a file is opened with >>, the operating system moves to the current end of the file before every write. If another process has added lines in the meantime, new lines still land after them rather than overwriting them. This matters when several processes share one log, as shown later.

Adding Timestamps

A log line without a time is of limited use. date with a format string produces a sortable timestamp:

echo "$(date '+%Y-%m-%d %H:%M:%S') backup started" >> app.log
tail -n 1 app.log
2026-11-22 03:01:15 backup started

The format %Y-%m-%d %H:%M:%S (year, month, day, hours, minutes, seconds) sorts correctly as plain text, so sort and grep work on log files without date parsing. Two other common formats are:

date -u '+%Y-%m-%dT%H:%M:%SZ'      # UTC, ISO 8601: 2026-11-22T03:01:15Z
date --iso-8601=seconds            # local time with offset (GNU): 2026-11-22T03:01:15+00:00

UTC timestamps avoid confusion when servers run in different time zones or when clocks change for daylight saving time.

Bash 4.2 and later can format the time without starting the date program, using %(...)T in printf (lesson 30). The argument -1 means the current time:

printf '%(%Y-%m-%d %H:%M:%S)T %s\n' -1 "printf builtin" >> app.log

This writes a line such as 2026-11-22 03:01:15 printf builtin. In scripts that log many lines, avoiding one date process per line saves noticeable time.

A Reusable log Function

Writing the timestamp and the file name on every line is repetitive and easy to get wrong. A small function (lesson 88) puts the format in one place:

LOG_FILE=./script.log

log() {
    local level=$1
    shift
    printf '%s [%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$level" "$*" >> "$LOG_FILE"
}

log INFO  "starting"
log WARN  "disk at 91%"
log ERROR "cannot reach db.example.org"

script.log now contains:

2026-11-22 03:01:15 [INFO] starting
2026-11-22 03:01:15 [WARN] disk at 91%
2026-11-22 03:01:15 [ERROR] cannot reach db.example.org

How it works:

  • The first argument is the level. shift removes it, so "$*" joins the remaining arguments into the message with single spaces (lesson 43).
  • printf with %s placeholders prints the message as data. A message containing % characters, such as 91% or 50%d, is printed literally. Using the message as the format string, as in printf "$*\n", would treat %d as a placeholder.
  • "$LOG_FILE" is quoted, so a path with spaces works (lesson 111).
  • Levels such as INFO, WARN and ERROR make the log easy to filter:
grep -c ERROR script.log
grep WARN script.log
1
2026-11-22 03:01:15 [WARN] disk at 91%

Showing and Logging at the Same Time

When someone may be watching, the same line can go to the terminal and the log. tee -a appends its input to a file and also copies it to standard output (lesson 62):

log2() {
    printf '%s %s\n' "$(date +%H:%M:%S)" "$*" | tee -a both.log
}
log2 "hello"
03:01:15 hello

The same line is appended to both.log. Without -a, tee would truncate the file on every call.

For messages that are diagnostics rather than normal output, send the terminal copy to standard error with tee -a "$LOG_FILE" >&2, so the script's standard output stays clean for data (lesson 56).

Including the Script Name and Process ID

When several scripts write to one file, or one script runs several times at once, adding the script name and process ID makes each line traceable. ${0##*/} removes the directory part of the script path, and $$ is the process ID (lesson 43):

printf '%s[%d]: %s\n' "${0##*/}" "$$" "msg"
backup.sh[48211]: msg

This is the same name[pid]: message layout that system logs use.

Logging Command Output and Errors

Appending Standard Error

Error messages go to standard error, which >> alone does not capture. 2>> appends standard error to a file (lesson 59):

ls /nonexistent 2>> err.log
cat err.log
ls: cannot access '/nonexistent': No such file or directory

To append both streams to the same file, redirect standard output first and then point standard error at it (lesson 60):

{ echo out; echo err >&2; } >> both2.log 2>&1
cat both2.log
out
err

&>> file is a Bash shortcut for >> file 2>&1. Dash does not understand it: in a test, ls /nonexistent &>> dd.log under Dash printed the error on the terminal and left dd.log empty, because Dash read & as "run in the background" and >> dd.log as a separate redirection of standard output only.

Redirecting a Whole Block

Several commands in a group { ...; } share one redirection, so the file is opened once for the whole group:

{
    echo "== run =="
    echo "step 1"
    echo "step 2"
} >> group.log

All three lines are appended to group.log in order.

Sending the Rest of the Script to the Log with exec

exec with only redirections and no command changes where the current shell's own output goes, from that point until the script ends (lesson 60). A script can send everything to a log with a single line at the top:

#!/usr/bin/env bash
exec >> ex.log 2>&1

echo "this goes to the log"
ls /nonexistent
echo "done"

Running the script prints nothing on the terminal. ex.log contains:

this goes to the log
ls: cannot access '/nonexistent': No such file or directory
done

To keep seeing the output while logging it, combine exec with tee through process substitution (lesson 151):

#!/usr/bin/env bash
exec > >(tee -a ex2.log) 2>&1
echo "visible and logged"

The line appears on the terminal and in ex2.log. Because tee runs as a separate process, its last lines can appear on the terminal just after the script itself has finished.

If only part of the script should go to the log, save the original standard output on a spare descriptor first and restore it afterwards:

exec 3>&1          # save the terminal on descriptor 3
exec >> ex3.log    # send standard output to the log
echo "to log"
exec 1>&3 3>&-     # restore standard output and close descriptor 3
echo "back on terminal"

Only back on terminal appears on the terminal; to log is in ex3.log.

Keeping a Log Open on a Descriptor

Every >> file opens and closes the file again. In a loop that writes thousands of lines, opening the file once on a dedicated descriptor is faster:

exec 4>> fd.log
for i in 1 2 3; do
    echo "line $i" >&4
done
exec 4>&-
line 1
line 2
line 3

exec 4>> fd.log opens the file in append mode on descriptor 4, >&4 writes to it, and exec 4>&- closes it.

When the Log Cannot Be Written

If the log directory does not exist, or the file is not writable, the redirection fails, Bash prints an error, the command does not run, and its status is 1:

echo x >> nodir/a.log
bash: nodir/a.log: No such file or directory

Because a failed redirection skips the command, a failing log call does not stop the script by itself (unless set -e is active). Creating the directory at the start with mkdir -p and checking that the file is writable makes failures visible early:

mkdir -p -- "$(dirname -- "$LOG_FILE")" || exit 1
: >> "$LOG_FILE" || { echo "cannot write $LOG_FILE" >&2; exit 1; }

: >> "$LOG_FILE" appends nothing. : is the null command, so the line only opens the file for appending, which creates it if needed and fails if it cannot be written.

Common locations are /var/log/NAME.log for system services (usually writable only by root), ~/.local/state/NAME/ or ~/logs/ for a user's own scripts, and a path next to the script for development. Lesson 159 discusses running scripts with the least privilege needed.

Several Processes Writing to One Log

Append mode places each write at the current end of the file, so separate processes do not overwrite each other's lines. In a test, four background processes each appended 500 lines to one file at the same time:

: > conc.log
for p in 1 2 3 4; do
    ( for i in $(seq 1 500); do echo "p$p line $i" >> conc.log; done ) &
done
wait
wc -l < conc.log
2000

All 2000 lines were present, each was complete, and each process contributed exactly 500. The lines of the four processes are interleaved, which is expected. This works because each echo writes a short line in a single write operation. Long messages, or a message built from several separate writes, can still be mixed with lines from another process.

When a group of lines must stay together, flock (from util-linux, standard on Linux but not on macOS) takes a lock on the file so that only one process writes at a time:

{
    flock 9
    echo "p$p a$i"
    echo "p$p b$i"
} 9>> lock.log >> lock.log

9>> lock.log opens the log on descriptor 9, and flock 9 waits until no other process holds the lock on it. The lock is released when the group ends and the descriptor closes. In a test with two processes writing three pairs each, every a line was directly followed by its b line. Lesson 171 uses the same tool to stop a script from running twice.

Keeping Logs from Growing Forever

A log that is only ever appended to grows without limit. A simple size check at the start of a script moves a large log aside:

max=5000
size=$(wc -c < big.log)
if (( size > max )); then
    mv -- big.log big.log.1
fi

wc -c < file prints only the byte count, without the file name. stat -c %s file gives the same number with GNU stat. After the move, the next >> creates a fresh big.log. On most Linux systems, the logrotate service handles rotation, compression and deletion of old logs; lesson 165 builds a rotation script.

The System Log with logger

Instead of managing its own file, a script can send messages to the system log with logger:

logger -t myscript "test message"

-t sets the tag that appears in front of the message. On systemd systems the message can be read with journalctl -t myscript; on others it usually goes to /var/log/syslog or /var/log/messages. The system log handles timestamps, rotation and permissions automatically, which suits scripts installed as services.

A Complete Logging Setup

This header combines the pieces into a starting point for unattended scripts:

#!/usr/bin/env bash
LOG_FILE=${LOG_FILE:-$HOME/logs/backup.log}

mkdir -p -- "$(dirname -- "$LOG_FILE")" || exit 1
: >> "$LOG_FILE" || { echo "cannot write $LOG_FILE" >&2; exit 1; }

log() {
    local level=$1
    shift
    printf '%(%Y-%m-%d %H:%M:%S)T %s[%d] [%s] %s\n' -1 "${0##*/}" "$$" "$level" "$*" >> "$LOG_FILE"
}

log INFO "backup started"
if tar -czf /tmp/home-backup.tar.gz -C "$HOME" documents 2>> "$LOG_FILE"; then
    log INFO "backup finished"
else
    log ERROR "tar failed with status $?"
    exit 1
fi
  • ${LOG_FILE:-...} lets the caller choose another log file through the environment (lesson 45).
  • The directory and file are checked before any work starts.
  • Each line carries a timestamp, the script name, the process ID and a level.
  • Errors from tar are appended to the same log with 2>>, between the script's own lines.
  • Inside the else branch, $? still holds the exit status of the tar command tested by if.

A successful run followed by a run with the documents folder missing left this log:

2026-11-22 03:02:14 backup.sh[812] [INFO] backup started
2026-11-22 03:02:14 backup.sh[812] [INFO] backup finished
2026-11-22 03:02:14 backup.sh[821] [INFO] backup started
tar: documents: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
2026-11-22 03:02:15 backup.sh[821] [ERROR] tar failed with status 2

The process IDs show which lines belong to which run, and the second run ended with status 1.

The examples were run with Bash 5.2.21, GNU coreutils 9.4, util-linux (flock, logger) and Dash. Timestamps and the process ID 48211 are sample values; error messages are shown in their interactive form.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Appending Logs to a File and get answers drawn from it.

Signed-in readers only.