>> /dev/null 2>&1

>> /dev/null 2>&1 

I know what the /dev/null part in bash script stands for, but what does 2>&1 mean and why and when would I use it?

So >> gets stuff redirected (or rather ‘appended’) to /dev/null, which is sort of the silent trash can on a Linux system. You typically use it when you don’t want your program to echo to STDOUT, i.e. produce visual output.

The three common file descriptors in Bash for STDIN, STDOUT and STDERR are 0, 1 and 2.

Programs that you run typically direct their main output to STDOUT so when you are redirecting the default or standard output of a file to >> /dev/null, you are redirecting 1 to /dev/null.

When you are running a program and you want to avoid any output to be shown or printed anywhere you can redirect it to /dev/null. So there we have you covered for the first part.

# But try the following
$ ls -l file_that_exists >> /dev/null

# no output, that's good!

# but now when you run
$ ls -l ndasfds >> /dev/null
ls: cannot access 'ndasfds': No such file or directory

Even with STDOUT being redirected to /dev/null, the error message still got redirected to the console. If this was part of a script it could have broken it or maybe we would just avoid this to show for security reasons.

# So that's when you can use >> /dev/null 2>&1
$ ls -l ndasfds >> /dev/null 2>&1

# No output, enjoy the silence! :)