BudiBadu Logo
Samplebadu

Bash by Example: Append File

Bash 5.0+

Adding content to the end of a file using the >> append redirection operator without truncating existing data, understanding append-only logging patterns for maintaining audit trails, implementing log rotation strategies, using append mode for incremental backups, and ensuring data integrity during concurrent append operations.

Code

#!/bin/bash

file="log.txt"

# Initialize file
echo "Log Start: $(date)" > "$file"

# Append single line
echo "Event 1 happened" >> "$file"

# Append multiple lines
echo "Event 2 happened" >> "$file"
echo "Event 3 happened" >> "$file"

# Append command output
ls -l "$file" >> "$file"

echo "--- Final Log Content ---"
cat "$file"

rm "$file"

Explanation

To add content to the end of an existing file without losing the current data, use the append operator >>.

If the file does not exist, >> will create it, just like >. If it does exist, the new data is written starting at the end of the file.

This is extremely common for logging, where you want to keep a history of events rather than just the latest one.

Code Breakdown

6
We use > first to initialize (or clear) the log file with a start timestamp.
9
The >> operator adds this line to the bottom of the file.
16
You can append the output of any command. Here we append the file listing of the log file itself into the log file.