Input/Output Redirection
Demonstrates stdin, stdout, stderr redirection including appending, merging streams, discarding output, and using file descriptors for advanced I/O control.
Code
#!/usr/bin/env bash
set -euo pipefail
logfile="output.log"
# Basic redirection
echo "Info message" > "$logfile"
echo "More info" >> "$logfile"
# Redirect stderr to /dev/null
ls /nonexistent 2>/dev/null || true
# Redirect both stdout and stderr
ls /etc /nonexistent &>"${logfile}.all" || true
# Redirect stdout and stderr separately
{
echo "This goes to stdout"
echo "This goes to stderr" >&2
} > /tmp/stdout.txt 2> /tmp/stderr.txt
# Here-string
read -r first second <<< "hello world"
echo "First: $first, Second: $second"
# Custom file descriptors
exec 3> /tmp/custom-fd.txt
echo "Line 1" >&3
echo "Line 2" >&3
exec 3>&-
# Read from file using fd
exec 4< /etc/hostname
read -r hostname <&4
exec 4<&-
echo "Hostname: $hostname"
# Redirect to multiple targets
echo "Broadcast" | tee /tmp/file1.txt /tmp/file2.txt /dev/null
# Conditional redirection
debug=true
if [[ "$debug" == true ]]; then
echo "Debug info" >&2
fiWhat the file does
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to ls and exec, chained through 5 pipes so each stage’s output feeds the next.
Caveats
- The pipeline is 5 stages deep — when it misbehaves, split the pipe and test the stages separately.
Statements that matter
ls /nonexistent 2>/dev/null || true
ls /etc /nonexistent &>"${logfile}.all" || true
} > /tmp/stdout.txt 2> /tmp/stderr.txt
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `ls`, `exec` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.