Bash Tutorial · Pipes and Text Processing · Lesson 8 of 30
Bash Redirection and Pipes
Send output to files, read input from files, separate errors, and chain commands with pipes.
Standard streams
Every program has three streams: stdin (0, input), stdout (1, normal output) and stderr (2, errors).
| Syntax | Meaning |
|---|---|
cmd > file |
stdout to a file (overwrite) |
cmd >> file |
stdout appended to a file |
cmd 2> file |
stderr to a file |
cmd > file 2>&1 |
both to the same file |
cmd < file |
stdin from a file |
| `cmd1 | cmd2` |
echo "first" > out.txt
echo "second" >> out.txt
cat out.txt
ls missing-file 2> errors.txt || true
echo "errors captured: $(wc -l < errors.txt) line"
ls out.txt missing-file > all.txt 2>&1 || true
sort all.txt
Output
first second errors captured: 1 line ls: cannot access 'missing-file': No such file or directory out.txt
Run this on your computer — see “Get Started” for setup.
Pipelines
Small tools combined with pipes solve big problems. This finds the most common words in a file:
cat > words.txt <<'EOF'
the cat sat on the mat
the dog sat on the log
EOF
tr ' ' '\n' < words.txt | sort | uniq -c | sort -rn | head -n 3
Output
4 the
2 sat
2 onRun this on your computer — see “Get Started” for setup.
/dev/null discards anything written to it: cmd > /dev/null 2>&1 silences a command.
Test yourself
What does 2>&1 mean?
Run two commandsSend stderr to wherever stdout is goingAppend to file 1Redirect stdin to stderr
Show answer
Answer: Send stderr to wherever stdout is going