Menu
Use streams, pipes and redirects
“Standard input, output and error, redirecting them to files, piping commands together, tee, command substitution and xargs.”
Every Linux command talks through three channels: one for input, one for normal output and one for errors. Once you know them, you can send output into a file, throw errors away, feed a file into a command, or connect commands together so the output of one becomes the input of the next.
This is the glue that makes the small tools from text filters useful. It’s also on the exam with a lot of weight, and the questions are full of tricky details like the order of 2>&1.
The three standard streams#
Every process starts with three open streams, each with a number called a file descriptor:
| Number | Name | Short | Default |
|---|---|---|---|
| 0 | Standard input | stdin | The keyboard |
| 1 | Standard output | stdout | The terminal |
| 2 | Standard error | stderr | The terminal |
Output and errors both land on your screen, so they look the same. But they’re separate streams, and you can send them to different places. Try ls on one file that exists and one that doesn’t:
ls /etc/hostname /nopels: cannot access '/nope': No such file or directory
/etc/hostnameThe first line came through stderr, the second through stdout.
Redirecting output: > and >>#
> sends stdout to a file instead of the screen. The file is created, or emptied first if it already exists. >> appends to the end instead:
echo one > list.txt
echo two >> list.txt
cat list.txtone
twoErrors still show on screen, because > only moves stream 1:
ls /etc/hostname /nope > out.txt
cat out.txtls: cannot access '/nope': No such file or directory
/etc/hostnameThe error was printed right away, and only /etc/hostname ended up in the file.
Warning
> empties the file before the command even starts. sort data.txt > data.txt leaves you with an empty file, because the shell wipes data.txt before sort reads it. Write to a new file, or use sort -o data.txt data.txt.
To protect yourself from overwriting files by accident, switch on noclobber. Then > refuses to overwrite, and >| forces it:
set -o noclobber
echo three > list.txt
echo three >| list.txt
set +o noclobberbash: list.txt: cannot overwrite existing fileRedirecting errors: 2> and 2>>#
Put the stream number in front of the > to redirect a different stream. 2> sends stderr to a file:
ls /etc/hostname /nope 2> errors.txt
cat errors.txt/etc/hostname
ls: cannot access '/nope': No such file or directoryThe special file /dev/null throws away everything written to it. It’s perfect for hiding noise, like the “Permission denied” messages from find:
find / -name "*.conf" 2>/dev/nullBoth at once: 2>&1 and &>#
2>&1 means “send stderr to wherever stdout goes right now”. Redirections are processed left to right, so the order matters:
ls /etc/hostname /nope > all.txt 2>&1 # both streams in the file
ls /etc/hostname /nope 2>&1 > only.txt # errors on screen, output in the fileIn the first line, stdout points at all.txt first, then stderr is copied to it. In the second, stderr is copied to the terminal (where stdout still points) and only then stdout moves to the file.
Bash has a shorter form that does the first version:
| Syntax | Meaning |
|---|---|
cmd > file | stdout to file (overwrite) |
cmd >> file | stdout to file (append) |
cmd 2> file | stderr to file |
cmd 2>> file | stderr to file (append) |
cmd > file 2>&1 | Both to file (works in every shell) |
cmd &> file | Both to file (Bash) |
cmd &>> file | Both appended to file (Bash) |
cmd > out 2> err | Each to its own file |
cmd 1>&2 or >&2 | stdout to stderr (used in scripts for error messages) |
Redirecting input: <, << and <<<#
< feeds a file into a command’s stdin:
wc -l < /etc/passwd
tr 'a-z' 'A-Z' < notes.txt34With <, the command reads a nameless stream, so wc can’t print a file name. That’s handy in scripts where you only want the number.
A here document (<<) feeds several lines that you type right there, until a line with only the end word:
cat <<EOF
Hello $USER
Today is $(date +%A)
EOFHello amin
Today is TuesdayVariables and $(...) are expanded inside. Quote the end word (<<'EOF') to keep everything literal, and use <<-EOF to strip leading tabs so you can indent the block in a script.
A here string (<<<) feeds a single string:
tr 'a-z' 'A-Z' <<< "here string"HERE STRINGPipes: |#
A pipe connects the stdout of one command to the stdin of the next. No temporary files, and both commands run at the same time:
ls /etc | wc -l
ps aux | grep sshd
cut -d: -f7 /etc/passwd | sort | uniq -cOnly stdout goes through the pipe. Errors still go to the screen. To send both through, use 2>&1 | or the Bash shortcut |&:
ls /etc/hostname /nope | wc -l
ls /etc/hostname /nope |& wc -lls: cannot access '/nope': No such file or directory
1
2The exit status of a pipeline is the exit status of the last command. Bash keeps all of them in the PIPESTATUS array:
false | true
echo "$? ${PIPESTATUS[@]}"0 1 0set -o pipefail makes a pipeline fail if any command in it fails, not just the last. That way an error early in a long pipeline isn’t hidden.Screen and file at once: tee#
Sometimes you want to watch output and save it too. tee reads stdin and writes it to stdout and to files, like a T-shaped pipe fitting:
ls /etc/hostname /nope | tee list.txt | wc -l
cat list.txtls: cannot access '/nope': No such file or directory
1
/etc/hostnametee -a appends instead of overwriting. You can give several files: cmd | tee a.txt b.txt.
tee also solves a classic sudo problem. This fails, because the redirection is done by your shell, not by sudo:
sudo echo "10.0.0.5 db01" >> /etc/hostsbash: /etc/hosts: Permission deniedThis works, because tee itself runs as root:
echo "10.0.0.5 db01" | sudo tee -a /etc/hostsAdd > /dev/null at the end if you don’t want to see the line echoed back.
Output as arguments: command substitution#
A pipe feeds output into stdin. But many commands don’t read stdin at all, they want arguments. $(command) runs a command and puts its output right into the command line:
echo "Kernel: $(uname -r)"
kill $(pgrep -f old-worker)
ls -l $(which bash)
TODAY=$(date +%F)
tar -czf "backup-$TODAY.tar.gz" ~/docsThe first line prints something like:
Kernel: 6.1.0-28-amd64The older form uses backticks: echo "Kernel: `uname -r`". It works the same, but $(...) is easier to read and can be nested: $(dirname $(which bash)). Use $(...) in new scripts and recognize backticks on the exam.
Output as arguments: xargs#
xargs does the same job as command substitution, but from a pipe. It reads items from stdin and runs a command with those items as arguments:
printf 'one\ntwo\nthree\n' | xargs echo
printf 'one\ntwo\nthree\n' | xargs -n 1 echo itemone two three
item one
item two
item threeWithout a command, xargs runs echo. It packs as many arguments into one run as possible, which is far faster than one run per item and avoids the “Argument list too long” error you get with a huge $(...).
| Option | Meaning |
|---|---|
-n N | At most N arguments per command run |
-I {} | Replace {} in the command with each item (one run per line) |
-0 | Items are separated by a null byte (pair with find -print0) |
-t | Print each command before running it |
-p | Ask before each run |
-r | Don’t run at all if the input is empty (GNU) |
-I lets you put the item anywhere in the command, not just at the end:
ls *.jpg | xargs -I {} cp {} /backup/{}.origSpaces in file names#
xargs splits its input on spaces and newlines, so a file called my file.log turns into two arguments:
find . -name "*.log" | xargs ls -lls: cannot access './my': No such file or directory
ls: cannot access 'file.log': No such file or directory
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 ./a.log
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 ./b.logThe fix: let find end every name with a null byte, which can never appear in a file name, and tell xargs to split on that:
find . -name "*.log" -print0 | xargs -0 ls -l-rw-r--r-- 1 amin amin 0 Dec 1 12:16 ./a.log
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 ./b.log
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 ./my file.logTip
find -exec cmd {} + does the same batching as xargs without the space problem. xargs is still the tool when the list comes from something other than find, like grep -l or a text file.
Exam checklist#
- File descriptors: 0 stdin, 1 stdout, 2 stderr.
/dev/nulldiscards anything written to it. >overwrites (empties first),>>appends,2>redirects errors,<reads a file as stdin.> file 2>&1sends both streams to the file;2>&1 > filedoes not.&>is the Bash shortcut for both.set -o noclobberstops>from overwriting;>|overrides it.<<EOFis a here document,<<<a here string.|pipes only stdout;|&(or2>&1 |) pipes stderr too. A pipeline’s exit status is the last command’s.tee filewrites to the screen and the file,tee -aappends.echo ... | sudo tee -a /etc/filewrites as root.$(cmd)and`cmd`put a command’s output into the command line.xargsturns stdin into arguments:-nper run,-I {}placeholder,-0withfind -print0for odd file names.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(lpic-103): Use streams, pipes and redirects"
[main 90c61bf] learn(lpic-103): Use streams, pipes and redirects
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: