Files and Pipelines
Redirects
Writing and Reading Files
Redirection connects command output and input to files. Scripts use it for temporary data, reports, and logs.
Program
Play the script to watch text move into a file and a line count come back out.
redirects.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
file="$(mktemp)"
printf 'alpha\nbeta\n' > "$file"
lines="$(wc -l < "$file")"
rm "$file"
echo "lines=$lines"
file ← /tmp/tmp.X
3file="$(mktemp)"4printf 'alpha\nbeta\n' > "$file"values this step/tmp/tmp.Xfilefile contents ← alpha, beta
3file="$(mktemp)"4printf 'alpha\nbeta\n' > "$file"5lines="$(wc -l < "$file")"values this stepalpha, betafile contents/tmp/tmp.Xfilelines ← 2
4printf 'alpha\nbeta\n' > "$file"5lines="$(wc -l < "$file")"6rm "$file"values this step2lines2 linesfile contentsfile ← removed
5lines="$(wc -l < "$file")"6rm "$file"7echo "lines=$lines"values this step/tmp/tmp.X → removedfileecho "lines=$lines"
6rm "$file"7echo "lines=$lines"outputlines=2values this step2lines
Write, Read, Clean Up
mktempcreates a temporary file path.>writes two lines into that file.<feeds the file intowc -l.rmremoves the temporary file after the count is saved.
printf stdout -> temp file
temp file -> wc stdin -> line count
redirection
`>` writes stdout to a file and `<` reads stdin from a file.
temporary file
`mktemp` creates a unique path for short-lived script data.
Exercise: redirects.sh
Write two lines to a temp file, read the line count with <, then remove the temp file