Writing and Appending to Files
In this page:
Writing Multiple Lines with a Loop
A common mistake is putting > inside a loop, which truncates the file every time. Instead, truncate once before the loop and use >> for each subsequent write.
Note: : > file or > file alone (with no command) is a quick way to truncate or create an empty file.
Example: Writing Multiple Lines with a Loop
#!/bin/bash
> items.txt
for item in one two three; do
echo "$item" >> items.txt
done
cat items.txt
rm -f items.txt
Login to try C/C++/Java/PHP code in the editor
Grouping Commands into One Write
Wrapping several commands in { ...; } and redirecting the whole group writes all of their combined output with a single file open, which is more efficient than redirecting each command separately.
Example: Grouping Commands into One Write
#!/bin/bash
{
echo "Report generated"
echo "Item count: 3"
date +%Y
} > report.txt
cat report.txt
rm -f report.txt
Login to try C/C++/Java/PHP code in the editor
Checking Write Success
A redirection can fail, for example if the target directory does not exist or permissions are wrong. Checking $? immediately after (or using set -e) catches that instead of silently continuing with a missing file.
Example: Checking Write Success
#!/bin/bash
if echo "data" > /tmp/write_test_$$.txt; then
echo "write succeeded"
cat /tmp/write_test_$$.txt
rm -f /tmp/write_test_$$.txt
else
echo "write failed" >&2
fi
Login to try C/C++/Java/PHP code in the editor
Appending Formatted Text with printf
printf gives exact control over formatting and newlines, which is often more predictable than echo, especially when the content includes variables that might start with a dash.
Note: printf never interprets a leading - in its arguments as an option, unlike some echo implementations.
Example: Appending Formatted Text with printf
#!/bin/bash
name="-weird-name"
printf '%s: %d\n' "$name" 42 >> log.txt
cat log.txt
rm -f log.txt
Login to try C/C++/Java/PHP code in the editor
- Repeating
>for every line in a loop, which resets the file back to empty on every iteration instead of building it up. - Not checking whether a write succeeded (e.g. disk full, permission denied), and assuming
>never fails. - Using
echoto write multi-line content without realizingprintfgives more precise control over newlines and formatting.
>inside a loop truncates on every iteration; use it once before the loop, then>>inside it.printf '%s\n' "$line" >> fileis a robust, predictable way to append a single line.- Grouping commands with
{ ...; } > filewrites the combined output of several commands with a single redirection. - Always check
$?(or useset -e) after critical writes in scripts that must not silently continue on failure.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: