Redirection: Sending Output to Files
Prerequisites: Viewing files
Every command has three standard streams:
| Stream | Number | Default |
|---|---|---|
standard input (stdin) |
0 | the keyboard |
standard output (stdout) |
1 | the screen |
standard error (stderr) |
2 | the screen |
Redirection connects these to files instead.
Output to a file
echo "first line" > notes.txt
echo "second line" >> notes.txt
cat notes.txt
echo "replaced" > notes.txt
cat notes.txt
first line
second line
replaced
>writes to a file, replacing its contents (or creating it).>>appends to the end.
Errors go separately
Error messages go to stderr, so > doesn't capture them:
echo "hello" > notes.txt
ls notes.txt missing.txt > output.txt 2> errors.txt
echo "stdout:"; cat output.txt
echo "stderr:"; cat errors.txt
stdout:
notes.txt
stderr:
ls: cannot access 'missing.txt': No such file or directory
2>redirects errors.&>redirects both output and errors to the same file (> file 2>&1does the same, and works in every shell).2> /dev/nullthrows errors away —/dev/nullis a special file that discards everything written to it.
Input from a file
printf '%s\n' banana apple cherry > fruits.txt
sort < fruits.txt
apple
banana
cherry
< feeds a file to a command's standard input. (sort fruits.txt also
works, since sort accepts file names — but not every command does.)
Here documents
A here document feeds several lines of text to a command's input:
cat > config.ini <<EOF
[server]
port=8080
EOF
cat config.ini
[server]
port=8080
Everything up to the line EOF becomes the input. It's the standard way
for scripts to write small files.
Common mistakes
sort data.txt > data.txt— the shell emptiesdata.txtbeforesortreads it, so you lose the data. Write to a new file, then move it.- Using
>when you meant>>, and overwriting a log.