Must-know cold
cmd > file (overwrite stdout) · cmd >> file (append)
cmd 2> file (stderr) · cmd > file 2>&1 (both; order matters)
cmd1 | cmd2 · cmd1 && cmd2 · cmd1 || cmd2
echo $? · exit 0 = success
cmd 2>&1 | tee log.txt
File descriptors
Definition: Integer handles for open I/O streams (0 stdin, 1 stdout, 2 stderr).
| FD | Name | Default |
|---|
| 0 | stdin | terminal (interactive) |
| 1 | stdout | terminal |
| 2 | stderr | terminal |
Operators & builtins
redirection
Definition: Send command stdin/stdout/stderr to files or other descriptors.
| Operator | Argument | Meaning | Example |
|---|
> | FILE | stdout overwrite (create/truncate) | echo hi > out.txt |
>> | FILE | stdout append | echo hi >> out.txt |
2> | FILE | stderr overwrite | cmd 2> err.txt |
2>> | FILE | stderr append | cmd 2>> err.txt |
2>&1 | — | Point stderr to wherever stdout currently goes | cmd >all.txt 2>&1 |
&> | FILE | Both stdout+stderr to FILE (bash) | cmd &> all.txt |
&>> | FILE | Append both (bash) | cmd &>> all.txt |
> | /dev/null | Discard stdout | cmd >/dev/null |
2> | /dev/null | Discard stderr | cmd 2>/dev/null |
> | /dev/null 2>&1 | Discard both | cmd >/dev/null 2>&1 |
< | FILE | stdin from FILE | cmd < input.txt |
<< | WORD | Heredoc until WORD | cat <<EOF ... EOF |
<<'WORD' | — | Heredoc; no expansion | cat <<'EOF' |
<<< | STRING | Herestring as stdin (bash, not POSIX sh) | grep x <<< "$var" |
>&2 | — | Write stdout to stderr (1>&2) | echo err >&2 |
| | — | Pipe stdout only to next stdin | grep E log | wc -l |
|& | — | Pipe stdout+stderr (bash 4+; same as 2>&1 |) | cmd |& tee all |
Critical order rule
| Form | Result |
|---|
cmd >file 2>&1 | stdout→file, then stderr copies that (file) — both in file |
cmd 2>&1 >file | stderr copies stdout first (still the terminal), then stdout→file — stderr stays on the terminal |
Recipes
| Combo | Meaning | Example |
|---|
cmd >out.txt 2>&1 | Classic both streams | |
cmd >>out.txt 2>&1 | Append both | Cron jobs |
cmd 2>/dev/null | Hide errors | Careful — can hide real failures |
cmd >out.txt 2>err.txt | Split streams | |
lists
Definition: Chain commands by success, failure, or unconditional sequence.
| Operator | Argument | Meaning | Example |
|---|
&& | — | Run right only if left exit 0 | mkdir d && cd d |
|| | — | Run right only if left non-zero | grep -q E f || echo none |
; | — | Run sequentially regardless | cmd1; cmd2 |
& | — | Background left command | longjob & |
! | cmd | Negate exit status | if ! cmd; then ... |
Flag combos
| Combo | Meaning | Example |
|---|
sudo apt update && sudo apt install -y x | Stop if update fails | |
cmd || true | Force success (mask failure — use carefully) | |
set -e in scripts | Exit on a failing simple command (see caveats) | Script safety |
exit status
Definition: The numeric code of the last command ($?); 0 means success.
| Item | Argument | Meaning | Example |
|---|
$? | — | Exit code of last command | echo $? |
exit | N | Exit shell/script with code N | exit 1 |
true | — | Always 0 | |
false | — | Always non-zero | |
set -e | — | Exit on a failing simple command; not in if, ||, && (except last), ! | Top of bash scripts |
set -u | — | Error on unset variables | |
set -o pipefail | — | Pipeline status is the last non-zero stage (others still run) | Important |
Convention: 0 = success · non-zero = failure (often 1; 127 = command not found)
Flag combos
| Combo | Meaning | Example |
|---|
cmd; echo $? | Inspect status | |
set -euo pipefail | Strict script mode | Production scripts |
tee
Definition: Copy stdin to a file and still pass it through to stdout.
| Option | Argument | Meaning | Example |
|---|
| (none) | FILE | Copy stdin to FILE and stdout | cmd | tee out.txt |
-a | FILE | Append to FILE | cmd | tee -a out.txt |
-i | — | Ignore SIGINT | Rare |
| multiple | F1 F2 | Write multiple files | cmd | tee a.txt b.txt |
Flag combos
| Combo | Meaning | Example |
|---|
cmd 2>&1 | tee log.txt | Capture both streams while watching | Install logs |
cmd | tee -a history.log | Append audit trail | |
xargs
Definition: Build and run command lines from stdin items (batch arguments).
| Option | Argument | Meaning | Example |
|---|
| (none) | CMD | Build args from stdin words (whitespace; also honors quotes) | echo a b | xargs ls |
-n | N | Max N args per command | xargs -n 1 echo |
-I | {} | Replace string with each line | xargs -I{} cp {} /bak/ |
-P | N | Parallel N processes | xargs -P 4 -n 1 cmd |
-0 | — | NUL-delimited input (safe spaces) | With find -print0 |
-d | DELIM | Input delimiter (GNU xargs) | xargs -d '\n' |
-r | — | Don’t run if empty input (GNU; BSD xargs already skips) | xargs -r rm |
-t | — | Print command before run | Debug |
-p | — | Prompt before each | Interactive |
Flag combos
| Combo | Meaning | Example |
|---|
find . -name '*.log' -print0 | xargs -0 -r rm | Safe delete by find | Spaces; -r avoids GNU rm with no args |
find . -name '*.txt' -print0 | xargs -0 grep -l ERROR | Grep many files | |
cat hosts | xargs -n 1 -P 4 ping -c 1 | Parallel ping | Careful load |
quoting
Definition: Control how the shell expands variables, globs, and spaces.
| Form | Meaning | Example |
|---|
'single' | Literal; no $, `, or $(...) | grep '$foo' f |
"double" | Expand $var, $(...), and backticks | echo "$HOME" |
\ | Escape next char | echo \$HOME |
$var vs "$var" | Unquoted splits on IFS whitespace | Always quote paths |
builtins
Definition: Shell built-ins. env, basename, and dirname are external utilities (/usr/bin/...), listed last.
| Command | Argument | Meaning | Example |
|---|
echo | STR | Print (builtin; flags differ from /bin/echo) | echo hello |
printf | FMT ARGS | Formatted print | printf '%s\n' "$x" |
read | VAR | Read line into VAR | read -r line |
export | VAR=val | Export env to children | export PATH=... |
command -v | NAME | Path of command (builtin) | command -v nginx |
type | NAME | How shell resolves name | type ls |
env | — | Print environment (not a builtin) | env | sort |
env -i | CMD | Empty env then CMD | Cron-like simulation |
basename | PATH | Final component (external) | basename /a/b |
dirname | PATH | Parent path (external) | dirname /a/b |
Common recipes
| Goal | Command |
|---|
| Save output | cmd > out.txt |
| Save output + errors | cmd > out.txt 2>&1 |
| Append log | cmd >> app.log 2>&1 |
| Watch + save | cmd 2>&1 | tee build.log |
| Hide noise | cmd 2>/dev/null |
| Pipeline count | grep ERROR app.log | wc -l |
| Fail-fast chain | cmd1 && cmd2 && cmd3 |
| Fallback | cmd || echo 'failed' |
| Exit code | cmd; echo $? |
| Safe find delete | find . -name '*.tmp' -print0 | xargs -0 -r rm -f |
| Cron-like env test | env -i HOME="$HOME" PATH=/usr/bin:/bin /path/job.sh |
Pitfalls
2>&1 order with > — wrong order loses stderr.
- Unquoted
$var breaks on spaces — quote "$var".
- Pipelines: without
set -o pipefail, only the last command’s status counts. pipefail changes the status; it does not stop later stages.
cmd > file truncates the file before cmd runs — don’t use the same file as input naively.
xargs default splits on whitespace — use -0 with find -print0.
- Masking failures with
|| true hides CI-visible errors.
For more details, try man <command> in your terminal.