How to Append to File in Bash
• 2 min read
bash file operations append redirection
Quick Answer: Append to File in Bash
To append content to a file in Bash, use the >> redirection operator: echo "text" >> file.txt. This adds content to the end of the file without overwriting existing content. Use > (single) to overwrite instead.
Quick Comparison: File Appending Methods
| Method | Operator | Behavior | Best For |
|---|---|---|---|
| echo >> | >> | Append line | Simple text |
| cat >> | >> | Append block | Multiple lines |
| printf >> | >> | Formatted append | Precise formatting |
| tee -a | Pipe | Append + display | Logging |
| sed -i | In-place | Edit and append | Complex edits |
Bottom line: Use >> for simple appending, use cat for multiple lines.
Append content to files in Bash.
Method 1: Using >> Operator
echo "New line" >> myfile.txt
Appends to end of file (creates if doesn’t exist).
Method 2: Append Multiple Lines
cat >> myfile.txt << EOF
Line 1
Line 2
Line 3
EOF
Method 3: Append Variable Content
text="Important data"
echo "$text" >> logfile.txt
Method 4: Append with Timestamp
echo "[$(date)] New entry" >> log.txt
Differences: > vs >>
| Operator | Behavior |
|---|---|
> | Overwrite file (create if missing) |
>> | Append to file (create if missing) |
Practical Examples
Append Log Entry
#!/bin/bash
log_file="/var/log/myapp.log"
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >> "$log_file"
}
log "Application started"
log "Processing data"
log "Application ended"
Append with Condition
file="data.txt"
if [ -f "$file" ]; then
echo "New data" >> "$file"
else
echo "New data" > "$file" # Create if missing
fi
Append Command Output
# Append system info
echo "--- System Info ---" >> syslog.txt
uname -a >> syslog.txt
df -h >> syslog.txt
Append Multiple Files
# Combine files
cat file1.txt file2.txt file3.txt > combined.txt
# Or append sequentially
cat file1.txt >> combined.txt
cat file2.txt >> combined.txt
cat file3.txt >> combined.txt
Safe Append Pattern
#!/bin/bash
file="$1"
content="$2"
if [ -z "$file" ] || [ -z "$content" ]; then
echo "Usage: $0 <file> <content>"
exit 1
fi
echo "$content" >> "$file"
if [ $? -eq 0 ]; then
echo "Appended successfully"
else
echo "ERROR: Failed to append"
exit 1
fi
Key Points
>>appends;>overwrites- Always quote variables:
echo "$var" >> "$file" - Use dates/timestamps in logs for debugging
- Check for write permissions before appending
Common Use Cases
- Logging - Append events and errors
- Configuration - Add settings to config files
- Data collection - Accumulate results
- Backups - Combine multiple files