Lesson 6 of 8 · 0 of 1 exercises solved
Pipes & Redirection
Learn to send a command's output to a file or into another command. let you combine small tools into one useful command.
#!/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 commandsPractice
Shell exercise
3 checksSort, uniq and stderr
From data/songs.txt produce a de-duplicated, sorted list of the track numbers only and save it to numbers.txt. Then capture the error message from reading a file that does not exist into errors.log without it appearing on screen.
Practice shell — type help to see what is available.
Finished reading?1 exercise still open. You can come back to it later.
Tip: use the ← and → keys to move between lessons.