Redirecting output and input

Lesson 22 of 30 · Working with Linux

The shell can connect a program’s streams to files. These examples create or replace files, so use a new empty disposable directory. They assume a POSIX-style shell and Python 3.

python3 -c 'import sys; print("sun"); print("notice", file=sys.stderr)' > result.txt 2> message.txt
cat result.txt
cat message.txt

The shell opens the files before starting Python. The first cat displays sun; the second displays notice. > directs stdout (descriptor 1); 2> directs stderr. Both create a file if necessary and truncate an existing file, even if the command subsequently fails. Use >> or 2>> to append instead. Redirection cannot create missing parent directories.

printf 'moon\n' >> result.txt
cat result.txt

The file now contains two lines, sun and moon. printf writes a newline for \n. Avoid redirecting output to a file that the same command is reading: the shell may empty it before the program reads it.

To connect a file to stdin, use <:

wc -l < result.txt
wc -l result.txt

Both counts are 2; whitespace in output may vary. In the first command the shell opens the file as stdin. In the second, the filename is an argument and wc opens it; its output also includes the filename. Input redirection does not alter the source file. Not all programs read stdin; consult the program’s documentation.

Redirections are processed left to right. command > all.txt 2>&1 sends both streams to all.txt: first stdout is redirected, then stderr is connected to stdout’s current destination. In command 2>&1 > all.txt, stderr instead keeps the original stdout destination. These schematic commands are not instructions to run a program named command.