Reading & Writing Files
Redirection sends a command's output somewhere other than the screen — usually into a file — and reading a file back in line by line is one of the most common things a script actually does.
Writing output to a file
> overwrites a file with a command's output; >> appends to whatever is already there:
bash log-start.sh
#!/bin/bash echo "Job started at $(date)" > run.log echo "Step 1 complete" >> run.log echo "Step 2 complete" >> run.log
$ terminal
cat run.log
Terminal output
Job started at Tue Sep 8 14:10:02 UTC 2026 Step 1 complete Step 2 complete
Caution:
> overwrites silently, with no confirmation — running the first line of that script twice in a row replaces the whole log rather than adding to it. Use >> once you've created the file if you want to keep accumulating output.Reading a file line by line
A while read loop with input redirected from a file is the standard, safe way to process a file one line at a time:
bash read-lines.sh
#!/bin/bash while IFS= read -r line; do echo "Line: $line" done < names.txt
Terminal output (names.txt contains three names)
Line: Priya Line: Sam Line: Jordan
Note:
IFS= and -r aren't decoration — they matter. Without IFS=, leading and trailing whitespace on each line gets silently stripped. Without -r, a backslash in the line is treated as an escape character instead of a literal character. Together they make sure each line comes through exactly as it's written in the file. Avoid for line in $(cat file) for this — it splits on every space and newline, not just newlines, and mangles anything with spaces in it.