ShBash · Lesson 6 of 8
Pipes & Redirection
Pipes are how Unix tools talk to each other. Each small tool does one thing — pipes connect them into powerful pipelines. This is the Unix superpower.
Bash
#!/bin/bash
# Redirection
command > file.txt # redirect stdout to file (overwrite)
command >> file.txt # redirect stdout to file (append)
command 2> error.txt # redirect stderr to file
command 2>&1 # redirect stderr to stdout
command > all.txt 2>&1 # redirect both to file
command < input.txt # redirect file to stdin
command &> all.txt # bash shorthand for both stdout+stderr
# /dev/null — the bit bucket
command > /dev/null # discard stdout
command > /dev/null 2>&1 # discard everything
# Pipes — connect stdout of one command to stdin of next
ls -la | grep ".sh" # filter ls output
cat /etc/passwd | cut -d: -f1 | sort # get and sort usernames
ps aux | grep nginx | grep -v grep # find nginx processes
du -sh */ | sort -h # show dir sizes, sorted
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10 # top commands
# tee — write to file AND pass through to stdout
command | tee output.txt # see output AND save it
command | tee -a output.txt # append instead of overwrite
# xargs — build commands from stdin
find . -name "*.log" | xargs rm # delete all .log files
find . -name "*.py" | xargs wc -l # count lines in each file
echo "apple banana cherry" | xargs -n1 # one item per line
# Process substitution (bash-specific)
diff <(ls dir1/) <(ls dir2/) # compare output of two commands