Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Redirection

Direct answer

Redirection sends a command's input or output to files: > overwrite, >> append, < input from a file, 2> stderr, 2>&1 stderr to wherever stdout goes, &> both, and here-documents with <<.

When to use this

Use it to save output, silence errors or feed input, and when output ends up in the wrong place.

First 30 seconds

1. Where should stdout and stderr go?

2. Check the order: > file 2>&1.

3. Permission denied with sudo → use | sudo tee file.

4. File emptied unexpectedly → > truncated it; use >>.

5. Verify the file content afterwards.

Operational verification

shell opens the target files left to right → file descriptors set → command runs with them

Evidence · next step

For Shell & Bash → Redirection, continue with the first unproven Topic check: Map fd 0/1/2 and any custom descriptors before and after each left-to-right redirection. If that boundary is healthy, advance to the adjacent check: Confirm redirection target path, permissions, filesystem capacity and whether truncation/append semantics are intended. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
linux
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformlinux
Scope / prerequisiteUse it to save output, silence errors or feed input, and when output ends up in the wrong place.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

5 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Operational evidence path Verify boundary

parsed command → expand redirection words → open/duplicate/close file descriptors left-to-right → exec/builtin with resulting fd table → output/input effects → command status + consumer result

Healthy evidence: fd routing matches the intended left-to-right map, target files have expected content/metadata and command plus consumer behavior is correct.

Step 2 Verification and output interpretation Verify boundary

Existing fast checks for this Topic. - Map fd 0/1/2 and any custom descriptors before and after each left-to-right redirection.

  • Confirm redirection target path, permissions, filesystem capacity and whether truncation/append semantics are intended.
  • Separate shell redirection errors from target-command errors and capture both statuses/messages.
  • Read back output files/streams and verify the downstream consumer saw the expected content.

Verification chain. parsed command → expand redirection words → open/duplicate/close file descriptors left-to-right → exec/builtin with resulting fd table → output/input effects → command status + consumer result

Step 3 Commands Verify boundary
cmd > out.log 2>&1
cmd 2>/dev/null
cmd >> out.log
Step 4 Failure modes and next checks Narrow the fault

Suspicious evidence: a file is truncated before a failing command, descriptor order sends stderr to the terminal unexpectedly, or a redirection-open failure is misdiagnosed as application failure.

Step 5 Common mistakes Narrow the fault
  • Wrong order: 2>&1 > file.
Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points

Order matters: cmd > file 2>&1 sends both to the file; cmd 2>&1 > file does not. sudo echo x > /root/f fails because the shell, not sudo, opens the file — use echo x | sudo tee /root/f. > truncates the file before the command runs.

Key checks
  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — exit code of the last command
ReferenceWhat it is1 section · depth on demand

Core model

Reason in file-descriptor terms and left-to-right redirection order. Opening/truncating a file, duplicating fd 2 to fd 1, or redirecting both streams can produce materially different results depending on order; confirm permissions, target path and open behavior before running destructive redirections.

ReferenceImportant terms & boundaries5 sections · depth on demand

What this shows and what it does not

Redirection verification shows descriptor routing/open semantics and resulting data, not correctness of the command that consumes or produces the stream.

In depth

Redirection: order, appending and here-documents

Redirections attach a command's file descriptors to files or to other descriptors. The bash(1) manual page states that they're processed from left to right, so order matters:

  • ls > dirlist 2>&1 sends both standard output and standard error to the file.
  • ls 2>&1 > dirlist sends only standard output there, because stderr was duplicated onto the terminal before stdout was redirected.
  • &>file is equivalent to >file 2>&1, and >> appends.
  • With noclobber set, > refuses to overwrite existing regular files. >| overrides that.

Redirection forms

FormEffect
cmd > filestdout to a file (truncate)
cmd >> filestdout appended
cmd 2> errors.logstderr to a file
cmd > out.log 2>&1Both to one file
cmd &> out.logThe same, Bash shorthand
cmd 2>/dev/nullDiscard errors
cmd < input.txtstdin from a file
cmd <<< "$var"Here-string: stdin from a string (newline appended)
exec 3> fd3.logOpen file descriptor 3 for the rest of the script

Here-documents (manual)

With an unquoted delimiter, variables and commands inside the here-document are expanded. With a quoted delimiter (<<'EOF'), the text is passed literally. <<- strips leading tabs, which allows indenting the here-document in scripts.

Special file names

Bash understands /dev/stdin, /dev/stdout, /dev/stderr and /dev/fd/N. It also understands /dev/tcp/host/port and /dev/udp/host/port for simple network connections.

host$ ls /etc /nonexistent > out.txt 2>&1; wc -l < out.txt
host$ ls /etc /nonexistent 2>&1 > out.txt
ls: cannot access '/nonexistent': No such file or directory
host$ set -o noclobber; echo test > out.txt
bash: out.txt: cannot overwrite existing file
host$ echo test >| out.txt; set +o noclobber
host$ cat <<EOF > /tmp/motd
Host: $(hostname), generated $(date +%F)
EOF
host$ cat <<'EOF' > /tmp/script.sh
echo "$HOME stays literal here"
EOF
host$ timeout 2 bash -c 'exec 3<>/dev/tcp/10.30.0.11/22; head -1 <&3'
SSH-2.0-OpenSSH_9.6

Reading the example

The second command shows the order rule: the error still reached the terminal. The last command uses /dev/tcp to read an SSH server's banner without any extra tools, which is handy for quick port checks on minimal systems.

Documented example, not captured output.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

How it works at runtime

Redirection is part of Shell & Bash → Redirection. Redirection changes the file-descriptor destinations or sources of a command before execution, enabling files, here-documents, here-strings and descriptor duplication without changing the command's own syntax.

Topic-specific state model. Redirection changes the file-descriptor destinations or sources of a command before execution, enabling files, here-documents, here-strings and descriptor duplication without changing the command's own syntax.

Interpretation rule. - > file truncates/open attempts before the target command runs ≠ command success is required for data loss.

  • 2>&1 >file ≠ >file 2>&1 because descriptor duplication follows left-to-right evaluation.
  • Redirected stdout ≠ redirected stderr unless explicitly combined.
  • A shell can fail to open a redirection target ≠ the target program necessarily started.

Quick reference

Redirection operators:

SyntaxEffect
> f, >> fstdout to file (truncate / append)
2> fstderr to file
&> f or > f 2>&1both
< fstdin from file
<<EOF … EOFhere-document
<<< "text"here-string
> /dev/nulldiscard
cat > /etc/motd <<'EOF'
Authorised use only.
EOF
sudo tee /etc/sysctl.d/99-local.conf <<< 'vm.swappiness=10' > /dev/null

sudo echo x > /root/file fails because the redirection happens in your unprivileged shell — use sudo tee.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Limits and how it fails

Primary failure point. Redirection verification shows descriptor routing/open semantics and resulting data, not correctness of the command that consumes or produces the stream.

ReferenceConfiguration & state1 section · depth on demand

Configuration, persistence and lifecycle

Distribution/platform context. Pipes owns process-to-process stream wiring; stdin/stdout/stderr owns standard descriptor roles; File & Directory Management owns target-file lifecycle.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor doclinux current

Authoritative/upstream documentation reviewed for bounded claims in Shell & Bash → Redirection. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
bash redirectionshell redirect stdout stderr2>&1linux redirection
Embedded reference data

Quick lookup tables

Redirection operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Redirection.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateRedirection changes the file-descriptor destinations or sources of a command before execution, enabling files, here-documents, here-strings and descriptor duplication without changing the command's own syntax.Establish exactly what this Topic owns before crossing into another subsystem.
Fast verificationPin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test.Use the shortest evidence path first; a fast check is a boundary test, not blanket proof.
Verification chainparsed command → expand redirection words → open/duplicate/close file descriptors left-to-right → exec/builtin with resulting fd table → output/input effects → command status + consumer resultTrace requested/configured state through effective state to the observed workload result.
Failure boundaryRedirection verification proves descriptor routing/open semantics and resulting data, not correctness of the command that consumes or produces the stream.Stop broad troubleshooting at the first boundary that is not supported by evidence.
Positive evidenceCorrelated Linux file/text/shell evidence can establish this proof path: parsed command → expand redirection words → open/duplicate/close file descriptors left-to-right → exec/builtin with resulting fd table → output/input effects → command status + consumer resultUse this observation only for the specific claim it actually supports.
Evidence limitIt does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Redirection verification proves descriptor routing/open semantics and resulting data, not correctness of the command that consumes or produces the stream.Do not promote a local success signal into end-to-end or adjacent-dependency proof.
Next troubleshooting checkContinue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks.Continue to the next unresolved boundary while preserving the original test condition.

Redirection · operational reference

Compact Linux state, persistence, verification and boundary reference for fast lookup.

Reference boundaryRedirection
Topic pathShell & Bash → Redirection
Runtime stateRedirection changes the file-descriptor destinations or sources of a command before execution, enabling files, here-documents, here-strings and descriptor duplication without changing the command's own syntax.
Fast checks- Map fd 0/1/2 and any custom descriptors before and after each left-to-right redirection. - Confirm redirection target path, permissions, filesystem capacity and whether truncation/append semantics are intended. - Separate shell redirection errors from target-command errors and capture both statuses/messages. - Read back output files/streams and verify the downstream consumer saw the expected content.
Verification chainparsed command → expand redirection words → open/duplicate/close file descriptors left-to-right → exec/builtin with resulting fd table → output/input effects → command status + consumer result Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary.
Failure boundaryRedirection verification proves descriptor routing/open semantics and resulting data, not correctness of the command that consumes or produces the stream. Boundary chain: process/context → userspace configuration → kernel subsystem/resource → device/network/filesystem dependency → effective state → original workload.
Persistence ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?