Chapter 7 · Lesson 7 of 11
Linux for servers

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.

By the end you will

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.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • 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 | cmd2 connects the output of cmd1 to the input of cmd2.
  • cmd > file sends output to a file, replacing it.
  • cmd >> file appends to the file.
  • cmd < file feeds a file as input.
  • cmd 2> file sends 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#

bash
ls -l /etc | less
ps aux | grep nginx
sudo journalctl -u nginx -n 200 | grep -i error

Each 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#

bash
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:

bash
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/hosts

tee 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#

bash
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.csv
  • wc -l counts lines, wc -w words, wc -c bytes.
  • sort orders lines, -n sorts numbers, -r reverses, -u removes duplicates.
  • uniq collapses adjacent duplicates only, so sort first. -c prefixes counts.
  • cut -d: -f1 splits on a delimiter and picks a field.
  • head -n 10 keeps the first 10 lines of the stream.

A classic: the top five client IPs in an nginx access log.

bash
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -n 5

Step 5: awk basics#

awk reads lines, splits them on whitespace into fields $1, $2, and so on, and runs your code on each.

bash
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:

bash
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#

bash
wc -l errors.txt
cat errors.txt
ls -l all.log

If 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 > file empties the file before sort reads it. Write to a temp file and mv it.
  • Pipes hide failures. In a | b, the exit status is that of b. Use set -o pipefail in scripts.
  • Buffering delays output. Some tools buffer when piped, so tail -f log | grep x may lag. Use grep --line-buffered.
  • Locale changes sorting. sort uses locale rules. For plain byte order, use LC_ALL=C sort.
  • Spaces break xargs. Use -0 with null-terminated input, or -d '\n' in GNU xargs.
  • Globs expand early. grep * file expands * in the shell. Quote patterns.

Troubleshooting#

SymptomLikely causeFix
bash: /etc/hosts: Permission denied after sudo echo x >> /etc/hostsRedirect ran as youecho x | sudo tee -a /etc/hosts
bash: file: ambiguous redirectVariable is empty or has spacesQuote it: > "$FILE" and check it is set
bash: cannot overwrite existing filenoclobber is onUse >| or choose a new name
Output file is emptyOutput went to stderrAdd 2>&1 after the redirect
xargs: unmatched double quoteA file name contains a quote and xargs read it as inputUse find -print0 with xargs -0
rm: cannot remove 'b': No such file or directoryA name with spaces was splitUse -print0 and -0
Broken pipe messageThe reader exited early, such as headHarmless; ignore it or add 2>/dev/null
uniq -c shows the same line twiceDuplicates are not adjacentRun sort before uniq

Quick reference#

bash
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 -l

Redirects are also how a cron job keeps a log.

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.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1What does ls /nonexistent > out.txt 2>&1 write into out.txt?
2How do you append a line to a root-owned file as a normal user with sudo?
3Why use find -print0 with xargs -0?
4What does sort | uniq -c do to a list of lines?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios