I/O Redirection & File Descriptors
Beginnerv1.0.0
Master Unix I/O redirection — stdout/stderr control, file descriptors, here documents, process substitution, and designing robust data flow in shell scripts and pipelines.
Content
Overview
Unix I/O redirection controls where command input comes from and where output goes. Understanding stdout, stderr, file descriptors, and process substitution is essential for shell scripting and pipeline design.
Why This Matters
- -Error handling — separate error messages from data output
- -Logging — redirect output to files without losing console display
- -Pipelines — control data flow between commands precisely
- -Scripting — build robust scripts with proper output management
How It Works
Step 1: Basic Redirection
Step 2: Separate stdout and stderr
Step 3: Here Documents & Here Strings
Step 4: Advanced File Descriptors
Step 5: tee — Split Output
Best Practices
- -Use
2>&1to merge stderr into stdout for logging - -Use
teewhen you need both file output and console display - -Close file descriptors when done:
exec 3>&- - -Use
<<'EOF'(quoted) to prevent variable expansion in heredocs - -Redirect to
/dev/nullto silence unwanted output
Common Mistakes
- -Wrong order:
2>&1 > filedoes NOT capture stderr to file (use> file 2>&1) - -Forgetting to close custom file descriptors (resource leak)
- -Using
>when you mean>>(overwrites existing file) - -Not quoting heredoc delimiter when literals are needed
- -Redirecting inside a pipeline stage incorrectly
FAQ
Discussion
Loading comments...