I/O and Redirection
Control input/output streams, compose here-docs, and use process substitution.
Streams
- stdin (0), stdout (1), stderr (2)
Redirecting output/input
echo "hi" > out.txt # overwrite
echo "again" >> out.txt # append
cmd < in.txt # stdin from file
cmd > out.txt 2> err.txt # split stdout/stderr
cmd &> all.txt # both to same file (bash)
Pipelines
producer | filter | consumer
Exit status is that of the last command; use set -o pipefail to fail on any stage.
Here-strings and here-docs
cat <<< "$var" # here-string (stdin from variable)
cat <<'EOF' > script.sh # literal (no expansion)
#!/usr/bin/env bash
echo "Hello"
EOF
cat <<EOF | sed 's/x/y/g'
line x
EOF
Process substitution
diff <(sort a.txt) <(sort b.txt)
Creates named pipes for commands that expect file paths.
File descriptors
exec 3> log.txt
echo "log" >&3
exec 3>&-
Open/close custom FDs for advanced routing.
Summary
- Redirect stdin/stdout/stderr, use here-docs/strings, and process substitution for flexible pipelines