# Use streams, pipes and redirects

> Standard input, output and error, redirecting them to files, piping commands together, tee, command substitution and xargs.

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/streams-pipes-redirects/


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](../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:

```bash
ls /etc/hostname /nope
```

```text
ls: cannot access '/nope': No such file or directory
/etc/hostname
```

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

```bash
echo one > list.txt
echo two >> list.txt
cat list.txt
```

```text
one
two
```

Errors still show on screen, because `>` only moves stream 1:

```bash
ls /etc/hostname /nope > out.txt
cat out.txt
```

```text
ls: cannot access '/nope': No such file or directory
/etc/hostname
```

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

```bash
set -o noclobber
echo three > list.txt
echo three >| list.txt
set +o noclobber
```

```text
bash: list.txt: cannot overwrite existing file
```

## Redirecting errors: `2>` and `2>>`

Put the stream number in front of the `>` to redirect a different stream. `2>` sends stderr to a file:

```bash
ls /etc/hostname /nope 2> errors.txt
cat errors.txt
```

```text
/etc/hostname
ls: cannot access '/nope': No such file or directory
```

The special file `/dev/null` throws away everything written to it. It's perfect for hiding noise, like the "Permission denied" messages from `find`:

```bash
find / -name "*.conf" 2>/dev/null
```

## Both 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:

```bash
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 file
```

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

```bash
wc -l < /etc/passwd
tr 'a-z' 'A-Z' < notes.txt
```

```text
34
```

With `<`, 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:

```bash
cat <<EOF
Hello $USER
Today is $(date +%A)
EOF
```

```text
Hello amin
Today is Tuesday
```

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

```bash
tr 'a-z' 'A-Z' <<< "here string"
```

```text
HERE STRING
```

## Pipes: `|`

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:

```bash
ls /etc | wc -l
ps aux | grep sshd
cut -d: -f7 /etc/passwd | sort | uniq -c
```

Only stdout goes through the pipe. Errors still go to the screen. To send both through, use `2>&1 |` or the Bash shortcut `|&`:

```bash
ls /etc/hostname /nope | wc -l
ls /etc/hostname /nope |& wc -l
```

```text
ls: cannot access '/nope': No such file or directory
1
2
```

The exit status of a pipeline is the exit status of the **last** command. Bash keeps all of them in the `PIPESTATUS` array:

```bash
false | true
echo "$? ${PIPESTATUS[@]}"
```

```text
0 1 0
```

 (Side note: In scripts, `set -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:

```bash
ls /etc/hostname /nope | tee list.txt | wc -l
cat list.txt
```

```text
ls: cannot access '/nope': No such file or directory
1
/etc/hostname
```

`tee -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`:

```bash
sudo echo "10.0.0.5 db01" >> /etc/hosts
```

```text
bash: /etc/hosts: Permission denied
```

This works, because `tee` itself runs as root:

```bash
echo "10.0.0.5 db01" | sudo tee -a /etc/hosts
```

Add `> /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:

```bash
echo "Kernel: $(uname -r)"
kill $(pgrep -f old-worker)
ls -l $(which bash)
TODAY=$(date +%F)
tar -czf "backup-$TODAY.tar.gz" ~/docs
```

The first line prints something like:

```text
Kernel: 6.1.0-28-amd64
```

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

```bash
printf 'one\ntwo\nthree\n' | xargs echo
printf 'one\ntwo\nthree\n' | xargs -n 1 echo item
```

```text
one two three
item one
item two
item three
```

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

```bash
ls *.jpg | xargs -I {} cp {} /backup/{}.orig
```

### Spaces in file names

`xargs` splits its input on spaces and newlines, so a file called `my file.log` turns into two arguments:

```bash
find . -name "*.log" | xargs ls -l
```

```text
ls: 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.log
```

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

```bash
find . -name "*.log" -print0 | xargs -0 ls -l
```

```text
-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.log
```

> [!TIP]
> `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/null` discards anything written to it.
- `>` overwrites (empties first), `>>` appends, `2>` redirects errors, `<` reads a file as stdin.
- `> file 2>&1` sends both streams to the file; `2>&1 > file` does not. `&>` is the Bash shortcut for both.
- `set -o noclobber` stops `>` from overwriting; `>|` overrides it.
- `<<EOF` is a here document, `<<<` a here string.
- `|` pipes only stdout; `|&` (or `2>&1 |`) pipes stderr too. A pipeline's exit status is the last command's.
- `tee file` writes to the screen and the file, `tee -a` appends. `echo ... | sudo tee -a /etc/file` writes as root.
- `$(cmd)` and `` `cmd` `` put a command's output into the command line.
- `xargs` turns stdin into arguments: `-n` per run, `-I {}` placeholder, `-0` with `find -print0` for odd file names.


## Byte check

1. Which command saves **both** normal output and errors of `make` in `build.log`?
   - `make 2>&1 > build.log`
   - **`make > build.log 2>&1`** (correct)
   - `make 2> build.log`
   Redirections are read left to right. `> build.log` points stdout at the file first, then `2>&1` points stderr at the same place. In the other order, stderr is copied to the terminal before stdout moves.

2. You want to see the output of a command on screen **and** save it to a file. Which tool do you use?
   - `xargs`
   - **`tee`** (correct)
   - `cat`
   `tee` copies its standard input to standard output and to one or more files, like a T-shaped pipe fitting.

3. Why use `find . -name '*.log' -print0 | xargs -0 rm` instead of the same without `-print0` and `-0`?
   - It's faster
   - **It handles file names with spaces or newlines safely** (correct)
   - It asks before each delete
   By default `xargs` splits on whitespace, so `my file.log` becomes two arguments. `-print0` ends each name with a null byte, and `xargs -0` splits only on that.


