26 / 55 · 19 Linux & Command Line · Pipes and Redirection← prev⊞ allnext →☰ Read as one page
4.3Redirection
Redirection connects command input and output to files instead of the terminal.
Output Redirection
# Write output to a file (overwrite)
curl -s https://api.example.com/users > users.json
# Append output to a file
echo "Test run completed at $(date)" >> test-log.txt
# Write to a file and display on screen simultaneously
curl -s https://api.example.com/users | tee users.json
# Append with tee
echo "Another result" | tee -a test-log.txt
Error Redirection
Linux has three standard streams:
- stdin (0): Standard input
- stdout (1): Standard output (normal output)
- stderr (2): Standard error (error messages)
# Redirect only errors to a file
npm run test 2> errors.log
# Redirect both stdout and stderr to the same file
npm run test > output.log 2>&1
# Redirect stdout and stderr to separate files
npm run test > output.log 2> errors.log
# Discard all output (useful for scripts where you only care about the exit code)
curl -s https://api.example.com/health > /dev/null 2>&1
# Discard errors only (suppress "Permission denied" noise from find)
find / -name "config.json" 2>/dev/null
Input Redirection
# Read input from a file
sort < unsorted-list.txt
# Here document (inline input)
cat <<EOF > test-config.json
{
"baseURL": "https://staging.example.com",
"timeout": 30000
}
EOF
# Here string (single line input)
grep "error" <<< "This has an error in it"