02 / FILES AND STREAMS · LESSON 07

Input, output and redirection

Keep report data separate from diagnostic messages.

13 min · learn at your pace

Three streams

A command normally reads standard input (descriptor 0), writes normal results to standard output (1), and writes diagnostics to standard error (2). Redirection changes where a stream goes without changing the command’s arguments. cat < source.txt > copy.txt connects two files through cat.

> truncates an existing output file before the command runs. >> appends. Avoid reading from and redirecting to the same file: the shell may erase it before the program can read it. Write a separate report or temporary file instead.

Order matters

command > combined.txt 2>&1 sends stdout to a file and then makes stderr follow stdout. Reversing those redirects has a different meaning. For a human diagnostic use printf 'message\n' >&2; it should not contaminate a report a later program expects to parse.

A here-document supplies literal multiline input. Quote its delimiter when you want to prevent substitutions in the body. Both here-documents and ordinary descriptor redirection work in Bash 3.2. In this exercise reports and diagnostics intentionally go to separate files so their content can be checked independently.

Try an example.sh
cat < source.txt > report.txt
printf 'Copied source.txt\n' > diagnostics.txt
YOUR TURN

Put it into practice.

Copy `source.txt` unchanged into `report.txt` using input/output redirection. Write exactly `Copied source.txt` plus a newline to `diagnostics.txt`. Print nothing to the terminal, preserve the source, and replace both outputs on each run.

See an explained solution
One way to solve it.sh
cat < source.txt > report.txt || exit 1
printf 'Copied source.txt\n' > diagnostics.txt

The shell supplies file descriptors to cat. Separate paths prevent truncating the evidence before reading it.