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"
  1. file ← /tmp/tmp.X

    3file="$(mktemp)"4printf 'alpha\nbeta\n' > "$file"
    values this step/tmp/tmp.Xfile
  2. file contents ← alpha, beta

    3file="$(mktemp)"4printf 'alpha\nbeta\n' > "$file"5lines="$(wc -l < "$file")"
    values this stepalpha, betafile contents/tmp/tmp.Xfile
  3. lines ← 2

    4printf 'alpha\nbeta\n' > "$file"5lines="$(wc -l < "$file")"6rm "$file"
    values this step2lines2 linesfile contents
  4. file ← removed

    5lines="$(wc -l < "$file")"6rm "$file"7echo "lines=$lines"
    values this step/tmp/tmp.X removedfile
  5. echo "lines=$lines"

    6rm "$file"7echo "lines=$lines"
    outputlines=2
    values this step2lines

Write, Read, Clean Up

  1. mktemp creates a temporary file path.
  2. > writes two lines into that file.
  3. < feeds the file into wc -l.
  4. rm removes 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