Linux Basic — Reading & Writing Files
Reading & Writing Files
Almost every shell script reads input from somewhere and writes output somewhere else. Doing this safely — without corrupting data, losing newlines, or being broken by spaces in filenames — is a foundational scripting skill that many beginners get wrong.
This chapter shows the correct, modern, safe patterns for I/O in Bash.
What You Will Learn
By the end of this chapter you will be able to:
- Read files line-by-line correctly using
while read - Slurp a file into an array with
mapfile/readarray - Use
printfinstead ofechofor portable, predictable output - Perform atomic writes that never leave partial files
- Append to files safely from multiple writers using
flock - Use
teeto write to a file and stdout at the same time - Create race-free temporary files with
mktempand clean them up withtrap
Topics in This Chapter
| # | Topic | Description |
|---|---|---|
| 1 | Reading Files | The right way to read line-by-line |
| 2 | Writing Files | >, >>, printf, atomic writes |
| 3 | Appending to Files | Safe appends and flock |
| 4 | Writing with tee | Fan-out and sudo writes |
| 5 | Safe Temporary Files | mktemp + trap cleanup |
| 6 | Practice Exercises | Hands-on tasks |
Why This Matters
A real-world example you will write hundreds of times:
# ❌ The classic broken pattern — beginners write this every day
for line in $(cat users.txt); do
echo "Processing $line"
done
# Breaks on: spaces, tabs, wildcards (* expands!), empty lines
# ✅ The correct pattern
while IFS= read -r line; do
echo "Processing $line"
done < users.txt
# Survives spaces, special chars, and never glob-expands
The difference is the line between a script that works on your laptop and one that silently corrupts production data.
Next → Reading Files