On this page
- What are stdin, stdout and stderr?
- How do you redirect output and errors to files?
- How do pipes chain commands together?
- Why does a pipeline report success when a step failed?
- What does xargs do?
- How do you use xargs safely with file names?
- How do you run jobs in parallel with xargs?
- What other redirection tricks are useful?
- What goes wrong most often?
- Questions
What are stdin, stdout and stderr?
Every process starts with three open streams: standard input (file descriptor 0), standard output (1) and standard error (2). Normal results go to stdout and messages go to stderr, which is why errors still show on screen when you redirect output to a file.
ls /etc /nonexistent
ls /etc /nonexistent > out.txt # errors still on screen
ls /etc /nonexistent 2> err.txt # only errors captured
ls -l /proc/self/fd/Keeping the two apart is a feature: you can save clean data while still noticing problems.
How do you redirect output and errors to files?
Put the operator after the command. Order matters when you combine streams.
date > now.txt # create or overwrite
date >> history.txt # append
cmd > all.log 2>&1 # stdout and stderr to one file
cmd &> all.log # same, Bash shorthand
cmd 2>/dev/null # discard errors
cmd > out.log 2> err.log # separate files
sort < names.txt # read stdin from a file2>&1 means "send stream 2 where stream 1 currently goes", so it must come after > all.log. Written the other way round, errors still reach the terminal. Bash also offers set -o noclobber, which stops > from overwriting an existing file by accident; use >| to force it. Redirects run as your user, so writing to root-owned files needs sudo tee, as shown in echo, tee and wc.
How do pipes chain commands together?
A pipe connects the stdout of the left command to the stdin of the right one, and both run at the same time. Long pipelines let small tools each do one step.
# ten IPs with the most requests in an Nginx access log
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
# biggest folders under /var
sudo du -xh --max-depth=1 /var 2>/dev/null | sort -h | tail -n 5
# include errors in the pipe
cmd 2>&1 | grep -i error
cmd |& grep -i error # Bash shorthand for the sameOnly stdout flows through a plain pipe. See sed and awk and grep for the filters that usually sit in the middle.
Why does a pipeline report success when a step failed?
By default the exit status of a pipeline is that of the last command only. Turn on pipefail so the pipeline fails if any stage fails.
false | true; echo $? # prints 0
set -o pipefail
false | true; echo $? # prints 1
cmd1 | cmd2; echo "${PIPESTATUS[@]}" # status of every stagePut set -o pipefail at the top of scripts, as part of the approach in error handling with set -euo pipefail.
What does xargs do?
xargs reads items from stdin and runs a command with those items as arguments. Many tools (rm, chmod, gzip) do not read file names from stdin, so xargs bridges the gap.
printf '%s\n' a b c | xargs echo
printf '%s\n' a b c | xargs -n 1 echo item
cat hosts.txt | xargs -I{} ping -c 1 {}
xargs -a hosts.txt -n 1 host-n 1: one item per command run.-I{}: run once per line and put the item where{}appears.-a file: read items from a file instead of stdin.-r(--no-run-if-empty): do nothing when the input is empty; without it, GNU xargs runs the command once with no arguments.
How do you use xargs safely with file names?
Separate names with null bytes. Spaces, quotes and newlines in file names break plain xargs, but no file name can contain a null byte.
find /var/www -name '*.log' -mtime +30 -print0 | xargs -0 -r ls -l
find /var/www -name '*.log' -mtime +30 -print0 | xargs -0 -r rm -v
grep -rlZ "old.example.net" /etc/nginx | xargs -0 -r sudo sed -i 's/old.example.net/app.example.net/g'Always run the listing version (with ls or echo) before the destructive one. grep -Z prints null-terminated names, the partner of -print0. For simple cases, find ... -exec cmd {} + does the same batching without xargs; the find guide covers it.
How do you run jobs in parallel with xargs?
Add -P with the number of parallel processes. Combined with -n, this spreads work over your vCPUs.
nproc
find ~/images -name '*.png' -print0 | xargs -0 -r -n 1 -P "$(nproc)" optipng -quiet
xargs -a hosts.txt -P 8 -I{} sh -c 'ping -c1 -W1 {} >/dev/null && echo "{} up"'Parallel output lines can interleave, so write results to per-item files when order matters. On a plan with shared vCPUs, running far more jobs than nproc reports mostly adds waiting, not speed. Install optipng from your package manager before trying the first example.
What other redirection tricks are useful?
Process substitution and here strings cover cases where a command insists on a file name or wants one line of input.
diff <(sort a.txt) <(sort b.txt) # compare sorted versions
wc -w <<< "count these four words" # here string
exec 3> ~/script.log; echo "note" >&3; exec 3>&- # extra descriptor
mkfifo /tmp/pipe1 # named pipe between two shellsHeredocs (<<EOF) for multi-line input are covered in heredocs and writing to files.
What goes wrong most often?
- File emptied:
sort file > filetruncates before sort reads. Write to a new file and rename, or usesort -o file file. - xargs splits names with spaces: switch to
-print0and-0. - "Argument list too long": a glob expanded to too many names. Pipe the list through xargs or use
find -exec ... +. - Errors missing from the log: put
2>&1after the file redirect. - Variables set inside a pipe vanish: each pipe stage runs in a subshell. Use
while read ... done < <(cmd)instead ofcmd | while read.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Pipes, redirection and xargs
What is the difference between a pipe and xargs?
A pipe passes data as a stream to stdin. xargs converts that stream into command-line arguments, for programs that expect names as arguments rather than input.
Is find -exec or xargs better?
Both are fine. -exec ... + is simpler and safe with any name; xargs adds parallel runs with -P and works with input from any command, not only find.
Where does /dev/null send output?
Nowhere. It is a special device that discards everything written to it and returns end of file when read.
Does the same syntax work in sh scripts?
Plain >, 2>&1 and pipes do. &>, |&, here strings, process substitution and PIPESTATUS are Bash features.
How do I see a pipeline's progress?
Insert pv (install the pv package) between stages, for example pv big.sql.gz | gunzip | wc -l, to see throughput and an estimated time.
More in Linux command line
- Copy files and directories with cp
- Move and rename with mv
- Create directories and empty files
- List files with ls, find your place with pwd
- Read files with cat, less and tail
- Find files with find and locate
- Search text with grep
- Edit and report text with sed and awk
- echo, tee and wc
- Edit files with nano
- Edit files with Vim
- Read manual pages
- Users and groups
- Ownership with chown and chgrp
- Symbolic and hard links