If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
read the transcript!
redirect to a file:
cmd > file.txt
terminal emulator into program, program out to file.txt, error out to terminal emulator
append to a file:
cmd >> file.txt
terminal emulator into program, program out to file.txt (append mode), error out to terminal emulator
send a file to stdin:
cmd < file.txt
file.txt into program, program out and err to terminal emulator
redirect stderr to a file:
cmd 2 > file.txt
terminal emulator into program, program out to nowhere, err out to file.txt
redirect stdout AND stderr:
cmd > file.txt 2>&1
terminal emulator into program, out and err to file.txt
pipe stdout:
cmd1 | cmd2
terminal emulator into program 1, 1 out to program 2 via pipe, 2 out to command line, program 2 out 1 and 2 to terminal emulator
pipe stdout AND stderr:
cmd1 2>&1 | cmd2
terminal emulator into program 1, 1 and 2 out to program 2 via pipe, program 2 out 1 and 2 to terminal emulator
three gotchas
cmd file.txt > file.txtwill delete the contents offile.txtsome people useset -o noclobber(in bash/zsh) to avoid this
but I just have “never read from redirect to the same file” seared into my memory.
sudo echo blah > /root/file.txtdoesn’t write to/root/file.txtas root. Instead, do:
echo blah | sudo tee /root/file.txt
or
sudo sh -c 'echo blah > /root/file.txt'
cmd 2>&1 > file.txtdoesn’t write both stdout and stderr tofile.txt. Instead, do:cmd > file.txt 2>&1
cat vs <
I almost always prefer to do:
cat file.txt | cmd
instead of
cmd < file.txt
it works fine & it feels better to me
using cat can be slower if if’s a GIANT file though
&> and &|
some shells support &> and &| to redirect/pipe both stdout and stderr
(also some shells use |& instead of &|)