How to use pipes and redirection in Linux
· Category: Linux
Short answer
Pipes (|) send one command's output to another's input; redirects (>, <>, 2>) write output to files or streams.
Steps
- Pipe output:
cat log.txt | grep error
- Redirect stdout to file:
echo "hello" > file.txt
- Append to file:
echo "world" >> file.txt
- Redirect stderr:
command 2> error.log
- Both stdout and stderr:
command >> log.txt 2>&1
Tips
teewrites to both stdout and a file:command | tee output.txt./dev/nulldiscards output:command > /dev/null 2>&1.- Use
xargsto convert piped text into command arguments.
Common issues
>overwrites existing files; use>>to append.- Order matters:
2>&1must come after the stdout redirect.