What's '2>&1' and '/dev/null'

1

1

I have been browsing through scripts and see 2>&1 & /dev/null everywhere. What are they? After googling, is it different for OS X than for Linux?

SurenNihalani

Posted 2012-08-28T22:39:44.563

Reputation: 599

Answers

2

There are three 'standard file streams' that Unix processes may make use of - stdin, stdout, and stderr - stdin usually reads input from the keyboard, and stdout and stderr usually go to your terminal window. stderr gets file descriptor number 2, and stdout gets file descriptor number 1. 2>&1 means "redirect all output to stderr to the same place that stdout is going". /dev/null is a character device - it simply discards anything written to it.

If you don't want to store the output of a script anywhere, and you don't want to see it on your terminal, you may redirect stderr to the same place as stdout with 2>&1, and then redirect stdout to /dev/null with > /dev/null

If you only were to redirect stdout with > /dev/null, you would still see errors on your terminal.

AlexWebr

Posted 2012-08-28T22:39:44.563

Reputation: 196

1

2>&1 is the information for the shell executing the script to redirect all the output including errors to specified destination like file or /dev/null

The /dev location in Linux systems provides the system with access to devices. One of those devices is a pseudo-device called null. /dev/null is an empty device - a vacuum if you will. It does nothing besides being a hole where you put something and it disapears. If you copy /dev/null to some file like:

cp /dev/null /tmp/foo

the specified file will be empty.

Detailed information about redirecting output you can be found here.

And here is a full definition of /dev/null:

On UNIX, this is a virtual-file that can be written to. Data written to this file gets discarded. It is similar to the file call NUL on Windows machines. Key point: When rooting a machine, intruders will often redirect logging to /dev/null For example, the command ln -s /dev/null .bash_history will cause the system to stop logging bash commands. Culture: In the vernacular, means much the same thing as black hole. Typical usage: if you don't like what I have to say, please direct your comments to /dev/null.

mnmnc

Posted 2012-08-28T22:39:44.563

Reputation: 3 637

1Please don't give examples using important system files such as grub.cfg. Deleting that file will render your system unbootable. – terdon – 2012-08-28T22:53:53.777

2I tried the grub.cfg thing and as soon as I entered the command, my computer shut down, the motherboard started playing pop goes the weasel and my LCD screen burst into flames displaying 0xdeadbeef in letters of fire. Don't try it. – Thomas – 2012-08-29T07:28:42.580