Redirections: stdin, stdout, and stderr
Every Unix process has three standard data streams. Understanding how to redirect them gives you powerful control over your scripts.
1. The Three Standard Streams
- stdin (0): Standard Input. Data the program reads from (usually the keyboard).
- stdout (1): Standard Output. Normal output printed by the program (usually the terminal screen).
- stderr (2): Standard Error. Error messages printed by the program (also usually the terminal screen).
2. Redirecting Output to Files
# Overwrite file with stdout (creates the file if it doesn't exist)
echo "Deploy complete" > deploy.log
# Append stdout to an existing file (does not overwrite)
echo "Step 2 complete" >> deploy.log
# Redirect stderr to a separate error file
ffmpeg -i input.mp4 output.webm 2> ffmpeg_errors.log
# Redirect both stdout and stderr to the same file
./build.sh > build.log 2>&13. Suppressing Output
To run a command silently, redirect both output streams to /dev/null (the system's "black hole"):
# Run command silently, suppressing all output
apt-get install -y nginx > /dev/null 2>&14. Reading stdin in Scripts
To accept piped input in a script using a while read loop:
#!/bin/bash
# Read each line from stdin
while IFS= read -r line; do
echo "Processing: $line"
donePublished on Last updated: