here's the final version of the "redirects cheat sheet" draft I posted a while back!

("The Secret Rules of the Terminal" is finished! 95 beta readers have read it! the copy editor is done! technical review is done! the illustrator has made the cover! It's going to be out on *****Tuesday June 24*****")

cmd > file.txt
cmd >> file.txt
cmd < file.txt
cmd 2> file.txt
cmd > file.txt 2>&1
cmd1 | cmd2
cmd1 2>&1 | cmd2

three gotchas:

1. cmd file.txt > file.txt  will delete the contents of file.txt

some people use set -o noclobber (in bash/zsh) to avoid this

But I just have "never read from and redirect to the same file" seared into my memory.

2. sudo echo blah > /root/file.txt doesn't write to /root/file.txt as root. Instead, do:

echo blah | sudo tee /root/file.txt

or

sudo sh -c 'echo blah > /root/file.txt'

3. cmd 2>&1 > file.txt  doesn't write both stdout and stderr to file.txt. Instead, do:

cmd > file.txt 2>&1

panel 3: cat vs <

I almost always prefer to do:

cat file.txt | cmd

instead of

cmd < file.txt

it usually works fine & it feels better to me

using cat can be slower if it's a GIANT file though

panel 4: &> and &|

some shells support &> and &| to redirect/pipe both stdout and stderr

(also some shells use |& instead of &|)
0
8
0

If you have a fediverse account, you can quote this note from your own instance. Search https://social.jvns.ca/users/b0rk/statuses/114717426933568419 on your instance and quote it. (Note that quoting is not supported in Mastodon.)