Appending Logs to a File
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.
shiftremoves it, so"$*"joins the remaining arguments into the message with single spaces (lesson 43). printfwith%splaceholders prints the message as data. A message containing%characters, such as91%or50%d, is printed literally. Using the message as the format string, as inprintf "$*\n", would treat%das 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
tarare appended to the same log with2>>, between the script's own lines. - Inside the
elsebranch,$?still holds the exit status of thetarcommand tested byif.
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.