← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 8 of 13

Writing and Appending to Files

Scripts can save text permanently to disk by writing to a new file or adding more lines onto an existing one.

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

bash
#!/bin/bash
> items.txt
for item in one two three; do
    echo "$item" >> items.txt
done
cat items.txt
rm -f items.txt

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

bash
#!/bin/bash
{
    echo "Report generated"
    echo "Item count: 3"
    date +%Y
} > report.txt
cat report.txt
rm -f report.txt

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

bash
#!/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

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

bash
#!/bin/bash
name="-weird-name"
printf '%s: %d\n' "$name" 42 >> log.txt
cat log.txt
rm -f log.txt
Common Mistakes
  1. Repeating > for every line in a loop, which resets the file back to empty on every iteration instead of building it up.
  2. Not checking whether a write succeeded (e.g. disk full, permission denied), and assuming > never fails.
  3. Using echo to write multi-line content without realizing printf gives more precise control over newlines and formatting.
Chapter Summary
  • > inside a loop truncates on every iteration; use it once before the loop, then >> inside it.
  • printf '%s\n' "$line" >> file is a robust, predictable way to append a single line.
  • Grouping commands with { ...; } > file writes the combined output of several commands with a single redirection.
  • Always check $? (or use set -e) after critical writes in scripts that must not silently continue on failure.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.