typestar

Redirection in Bash

Where output goes: files, appends, stderr and heredocs.

out=$(mktemp)

# > writes, >> appends, 2>&1 folds stderr into stdout
echo "first line" > "$out"
echo "second line" >> "$out"
ls /no/such/path >> "$out" 2>&1 || true

# a heredoc feeds multi-line input to stdin
cat >> "$out" <<'EOF'
from a heredoc
EOF

wc -l < "$out"
rm "$out"

How it works

  1. > truncates, >> appends, 2>&1 folds stderr in.
  2. A heredoc feeds multi-line stdin from the script itself.
  3. wc -l < file redirects input without a pipe.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
276
Tokens
49
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 37 seconds.

Type this snippet

Step 2 of 3 in Pipes & redirection, step 17 of 26 in Language basics.

← Previous Next →