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.

Create a free account to save this page, take notes and track your progress. Sign in

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`
Redirecting stdout and stderr
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:

A word-frequency pipeline
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 on

Run 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?

  1. Run two commands
  2. Send stderr to wherever stdout is going
  3. Append to file 1
  4. Redirect stdin to stderr
Show answer

Answer: Send stderr to wherever stdout is going

Was this page helpful?