Dualo
Bash / Shell Scripting

Pipes & redirections

Connect the output of one command to the input of another (`|`), or send it to a file (`>`, `>>`). The core composition tool of Unix.

1 min read

Every process has three default streams: stdin (input, FD 0), stdout (normal output, FD 1), stderr (errors, FD 2). Redirections let you wire them to files or to other commands.

Pipe |: sends stdout of the left command into stdin of the right. cat access.log | grep 500 | wc -l reads a file, keeps lines containing '500', counts them. Each piece is a small tool; the pipe composes them.

File redirection: cmd > file overwrites a file with stdout. cmd >> file appends. cmd < file feeds the file as stdin. cmd > /dev/null throws output away.

Errors go elsewhere: by default stderr is NOT piped. cmd | grep foo only sees stdout. If you also want to process errors, merge them first: cmd 2>&1 | grep foo. The 2>&1 means 'redirect FD 2 to wherever FD 1 currently points'.

Common idioms: cmd 2>/dev/null (silence errors), cmd >out.log 2>err.log (separate logs), cmd &>all.log (Bash shorthand for both into one file). Order matters: cmd 2>&1 >file does NOT do what you think — write it as cmd >file 2>&1.

Grounded on https://www.gnu.org/software/bash/manual/bash.html#Redirections

Next up

Variables & quoting

Store values, interpolate them, and — most importantly — quote them to survive spaces, globs, and special characters.