Input/Output Redirection

Demonstrates stdin, stdout, stderr redirection including appending, merging streams, discarding output, and using file descriptors for advanced I/O control.

BashCli Tooling

Code

snippet
#!/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
fi