Reference

Shell & command line

Read commands, quoting, streams, paths and scripts.

Scope and conventions

POSIX sh (2017 baseline), Bash additions and named Unix tools. Examples are independent fragments; file paths are illustrative. Bash-only syntax is labeled. macOS and Linux utility flags can differ.

Streams & pipelines

Recognize the three standard streams

POSIX sh

Descriptor 0 is stdin, 1 is stdout and 2 is stderr. Redirecting stdout alone does not capture diagnostic output.

Fragment

POSIX sh · Recognize the three standard streams
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
cat < input.txt > output.txt
printf 'problem\n' >&2

Write, append and combine output

POSIX sh

> creates or truncates a file. >> appends. 2>&1 duplicates the current destination of descriptor 1; redirections are processed left to right.

Fragment

POSIX sh · Write, append and combine output
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
./check.sh > run.log 2>&1
./check.sh >> run.log 2>&1

2>&1 > run.log leaves stderr at the old stdout destination.

Connect stdout to the next stdin

POSIX sh

| connects the left command’s stdout to the right command’s stdin. Stderr stays separate unless redirected.

Fragment

POSIX sh · Connect stdout to the next stdin
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
printf 'pear\napple\npear\n' | sort | uniq -c

Pipeline components can run concurrently; do not rely on a pipeline loop changing variables in the caller.

Know which pipeline status you observed

POSIX sh

In the 2017 POSIX baseline, the pipeline status comes from its last command. A successful consumer can hide a failed producer.

Fragment

POSIX sh · Know which pipeline status you observed
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
false | cat
printf '%s\n' "$?"
# 0: cat succeeded

Supply a literal multi-line input

POSIX sh

A quoted here-document delimiter suppresses expansions in the body. The closing delimiter must appear by itself.

Fragment

POSIX sh · Supply a literal multi-line input
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
cat <<'TEXT'
$name remains literal
second line
TEXT

Inspect and save the same stream

POSIX sh

tee copies stdin to stdout and files. tee -a appends rather than replacing the file.

Fragment

POSIX sh · Inspect and save the same stream
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
printf 'sample\n' | tee sample.log

The surrounding pipeline still has its own status rules.