Pipes, redirects and xargs in Linux (|, >, 2>&1, tee)
A pipe sends one command's output into the next command's input, redirects send output to files, and xargs turns lines of input into arguments for another command.
- Updated Nov 27, 2026
- Markdown
Combine commands with pipes, capture output and errors to files, write to root-owned files with sudo tee, and run xargs safely with find -print0.
- An Ubuntu or Debian server you can reach over SSH
The shell’s real power is that small commands can be joined. grep finds lines, sort orders them, uniq -c counts them, and a pipe passes the result along, so you can answer “which IP hit us most?” in one line. This lesson covers the plumbing and the mistakes that destroy files.
How it works#
Every process starts with three streams: standard input (stream 0), standard output (1) and standard error (2). By default, input comes from the keyboard, and both outputs go to the terminal. The shell can rewire them before the command runs.
cmd1 | cmd2connects the output ofcmd1to the input ofcmd2.cmd > filesends output to a file, replacing it.cmd >> fileappends to the file.cmd < filefeeds a file as input.cmd 2> filesends only errors to a file.
Because the shell sets up redirects, not the command, sudo cmd > file opens the file as you, not as root (see sudo). Remember that when you edit root-owned files, as covered in read and edit files on Linux.
Step 1: Pipes#
ls -l /etc | less
ps aux | grep nginx
sudo journalctl -u nginx -n 200 | grep -i errorEach stage reads from the one before it. Pipelines stop being useful when the first command can not produce output the next one understands, so test each stage on its own and add the next with | once it looks right. The journal examples work with journalctl.
Step 2: Redirect output and errors#
echo "first" > notes.txt
echo "second" >> notes.txt
ls /missing 2> errors.log
command > all.log 2>&1
command &> all.log
command > /dev/null 2>&1> overwrites without asking, so echo x > important.conf destroys that file. Use >> when you mean to add. For errors, 2> captures stream 2. command > all.log 2>&1 sends both streams to the same file. The order matters: 2>&1 > file sends errors to the terminal because stderr is duplicated before stdout moves. &> is a Bash shortcut for both.
/dev/null is a device that discards everything written to it. > /dev/null 2>&1 silences a command completely, which is common in cron lines. Use it with care, because you also hide real errors. Protect yourself with set -o noclobber in your shell so > refuses to overwrite an existing file, and then >| forces it.
Step 3: tee and sudo#
tee copies its input to a file and also to the screen, so you can save and watch at once:
sudo apt update | tee update.log
echo "deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp" | sudo tee /etc/sudoers.d/deploy
echo "extra line" | sudo tee -a /etc/hoststee file overwrites, tee -a file appends. This is the standard fix for sudo echo x > /etc/file, which fails because the redirect runs as you. Add > /dev/null after sudo tee to hide the echo of the text. Never write to a sudoers file this way without checking it with sudo visudo -c, see users, groups and sudo.
Step 4: Count, sort and cut#
wc -l access.log
sort names.txt | uniq
sort names.txt | uniq -c | sort -rn | head
cut -d: -f1 /etc/passwd
cut -d, -f2 data.csvwc -lcounts lines,wc -wwords,wc -cbytes.sortorders lines,-nsorts numbers,-rreverses,-uremoves duplicates.uniqcollapses adjacent duplicates only, so sort first.-cprefixes counts.cut -d: -f1splits on a delimiter and picks a field.head -n 10keeps the first 10 lines of the stream.
A classic: the top five client IPs in an nginx access log.
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -n 5Step 5: awk basics#
awk reads lines, splits them on whitespace into fields $1, $2, and so on, and runs your code on each.
awk '{print $1}' access.log
awk '{print $1, $9}' access.log
awk -F: '{print $1, $7}' /etc/passwd
awk '$9 == 500 {print $7}' access.log$1 is the first field, $NF the last, and $0 the whole line. -F: sets the separator. A pattern before the braces, such as $9 == 500, selects lines. That covers most server uses. Use single quotes so the shell leaves $1 alone.
Step 6: xargs#
xargs reads items from input and runs a command with them as arguments:
find /var/tmp -name "*.tmp" -print0 | xargs -0 ls -l
find /var/tmp -name "*.tmp" -print0 | xargs -0 rm
cat servers.txt | xargs -n 1 ping -c 1
grep -rl "oldname" src | xargs sed -i 's/oldname/newname/g'Without -0, xargs splits on any whitespace, so b file.tmp becomes two arguments, b and file.tmp, and you may delete the wrong thing. Pair find -print0 with xargs -0 every time. -n 1 runs the command once per item, and -I{} places each item inside the command: xargs -I{} cp {} /backup/. Add -p to be asked before each run, and -r (GNU) to skip the command if the input is empty.
Always preview first: run the same pipeline with ls or echo in place of rm before you swap in the destructive command, as in work with files safely.
Check it worked#
wc -l errors.txt
cat errors.txt
ls -l all.logIf a file is empty after a redirect, either the command printed nothing, or its output went to stderr and you needed 2>&1. If a file was supposed to grow and did not, you probably used > instead of >>.
Edge cases and gotchas#
- Reading and writing the same file.
sort file > fileempties the file before sort reads it. Write to a temp file andmvit. - Pipes hide failures. In
a | b, the exit status is that ofb. Useset -o pipefailin scripts. - Buffering delays output. Some tools buffer when piped, so
tail -f log | grep xmay lag. Usegrep --line-buffered. - Locale changes sorting.
sortuses locale rules. For plain byte order, useLC_ALL=C sort. - Spaces break xargs. Use
-0with null-terminated input, or-d '\n'in GNU xargs. - Globs expand early.
grep * fileexpands*in the shell. Quote patterns.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
bash: /etc/hosts: Permission denied after sudo echo x >> /etc/hosts | Redirect ran as you | echo x | sudo tee -a /etc/hosts |
bash: file: ambiguous redirect | Variable is empty or has spaces | Quote it: > "$FILE" and check it is set |
bash: cannot overwrite existing file | noclobber is on | Use >| or choose a new name |
| Output file is empty | Output went to stderr | Add 2>&1 after the redirect |
xargs: unmatched double quote | A file name contains a quote and xargs read it as input | Use find -print0 with xargs -0 |
rm: cannot remove 'b': No such file or directory | A name with spaces was split | Use -print0 and -0 |
Broken pipe message | The reader exited early, such as head | Harmless; ignore it or add 2>/dev/null |
uniq -c shows the same line twice | Duplicates are not adjacent | Run sort before uniq |
Quick reference#
cmd > file # overwrite
cmd >> file # append
cmd 2> err.log # errors only
cmd > all.log 2>&1 # both
cmd > /dev/null 2>&1 # silence
echo x | sudo tee -a /etc/file # root write
sort | uniq -c | sort -rn # frequency count
cut -d: -f1 file # pick a field
awk '{print $1}' file
find . -name "*.tmp" -print0 | xargs -0 ls -lRedirects are also how a cron job keeps a log.
Related lessons#
- Essential Linux commands for servers: the building blocks you are chaining.
- Schedule tasks with cron: where output redirects keep jobs quiet.
- Read logs with journalctl: a source that pipes well into grep.
- Read container logs: the same filters on Docker output.
For a log-reading example, see Docker container restarting in a loop.
Next#
Put redirects to work in scheduled jobs with cron vs systemd timers.
Try it: Pipes, redirects and xargs
Count requests per status code from a sample access log, save results and use xargs safely.
Want a real machine? Free browser labs: Killercoda
Check what you learned
Frequently asked questions
What is the difference between > and >> in Linux?
The > operator writes output to a file and replaces anything already there, while >> appends to the end of the file. Using > on the wrong file destroys its contents.
What does 2>&1 mean?
It sends standard error (stream 2) to the same place as standard output (stream 1). Put it after the file redirect, as in command > out.log 2>&1, so both streams reach the file.
Why does sudo echo text > /etc/file fail with permission denied?
The redirect is performed by your shell, which is not running as root. Use echo text | sudo tee /etc/file instead, so the write runs as root.
When should I use xargs instead of a loop?
Use xargs when you have a list of items from another command and want to run one command on them, especially with find -print0 and xargs -0 to handle spaces in names.
Sources
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.