Script Valley
Bash Scripting for Developers
Shell FundamentalsLesson 1.4

Bash input and output redirection fundamentals

stdin stdout stderr, file descriptors 0 1 2, redirect operators, /dev/null, tee command, heredoc, pipe operator

Three Standard Streams

stdin stdout stderr streams

Every process has three open file descriptors by default: stdin (0) reads input, stdout (1) writes normal output, stderr (2) writes errors. Redirection lets you rewire these connections.

# Redirect stdout to a file
echo "log entry" > app.log      # overwrite
echo "log entry" >> app.log     # append

# Redirect stderr
ls /bad 2> errors.log

# Redirect both stdout and stderr
command > out.log 2>&1

# Discard output completely
command > /dev/null 2>&1

Pipes: Connect Commands

The pipe operator | connects stdout of one command to stdin of the next:

cat /var/log/syslog | grep "ERROR" | wc -l
# Count error lines without creating temp files

Heredoc: Multiline Input

cat << 'EOF'
This text goes to stdout.
Variables like $HOME are NOT expanded
because we quoted EOF.
EOF

# Without quotes, variables expand:
cat << EOF
Home is $HOME
EOF

tee: Write and Pass Through

command | tee output.log
# Writes to file AND prints to terminal simultaneously
# Essential for logging long-running scripts

Use 2>&1 before piping to tee if you want stderr captured too: command 2>&1 | tee full.log.

Up next

Command substitution and arithmetic in Bash

Sign in to track progress

Bash input and output redirection fundamentals โ€” Shell Fundamentals โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley