DEV Community

Cover image for Stupid Short: Bash's |, >, >>, <, 2>>, 2> Operators

Stupid Short: Bash's |, >, >>, <, 2>>, 2> Operators

Lee on September 14, 2019

This is meant to be a stupid-short introductory and reference guide for quickly understanding these Bash operators: &gt;, 1&gt;, &gt;&gt;, 1&gt;&gt...
Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Here's one more I'm using sometimes:

$ call-foo > out_and_err.txt 2>&1

So here I'm redirecting STDERR to the address of STDOUT, which is a file called "out_and_err.txt".

Collapse
 
fennecdjay profile image
Jérémie Astor

I think that in recent bash and zsh, one can use

call-foo &> out_and_err.txt
Collapse
 
sinewalker profile image
Mike Lockhart • Edited

This is my favourite "shut up, I don't want to see any output, even if it fails, just do, or don't do, the thing" shortcut:

call-foo &> /dev/null
Thread Thread
 
fennecdjay profile image
Jérémie Astor

I think you have a small typo here.
Shouldn't it read

call-foo &> /dev/null
Thread Thread
 
sinewalker profile image
Mike Lockhart

Thank you, fixed 😁

Thread Thread
 
fennecdjay profile image
Jérémie Astor

You're welcome.

Collapse
 
bananabrann profile image
Lee • Edited

I would've done call-foo > out-and-error.txt 2> out-and-error.txt; I've never heard of 2>&1 or &>. Very cool! Thanks for that!

What would be a practical application of print stdout and stderr to the same file?

@fennecdjay
@thorstenhirsch
@sinewalker

Thread Thread
 
sinewalker profile image
Mike Lockhart

Openssl prints diagnostic info to stderr and certificate info to stdout. If you want them both in the same filter stream, &> is very handy. Or if you want them all in the same single log file

Collapse
 
masedi profile image
Edi Septriyanto

What's & mean?

Collapse
 
ismiyati profile image
ismiyati
Collapse
 
ferricoxide profile image
Thomas H Jones II

Another really useful redirection-related BASHism: <( ):

Useful if, say, you want to check to see if a local file and an S3-hosted file are the same:

$ sha256sum <( aws s3 cp s3://BUKKIT1/file - ) ./file
d20c7a50c3ac734230b08dbe2cb9122634c2dd040eee56ebd8101bef455dbb88 */dev/fd/63
c204dbfa154fc4801bdaac298584815bbd1b4a968a2349dd17f1e7c459904d41 *file
Enter fullscreen mode Exit fullscreen mode

Similarly, can be used for things like diffing two streams:

diff <( aws s3 cp s3://BUKKIT1/file - ) <( aws s3 cp s3://BUKKIT2/file - )
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moopet profile image
Ben Sinclair

Another one people don't seem to use much is >| which will overwrite a file even if noclobber is on.

Collapse
 
hinchk profile image
Kasey

Makes truncating a breeze! |> logfile.log

Collapse
 
yaser profile image
Yaser Al-Najjar

I never looked these up before, though I use most of them almost everyday 😁

Thanks Pierson!

Collapse
 
bananabrann profile image
Lee

Haha, I was in the same boat!