Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if ( ) < /dev/null

Tags:

bash

unix

I can't wrap my head around this. Why would /dev/null be used as input to an if statement? What is the use of < /dev/null in the following?

if ( $PROG --version ) < /dev/null > /dev/null 2>&1; then
        $PROG
else
        echo "failed"
        exit 1
fi

I (think) I understand that > /dev/null 2>&1 is just used to suppress any output from both stdout and stderr.

like image 737
Xu Wang Avatar asked Sep 11 '12 06:09

Xu Wang


People also ask

What does >/ dev null 2 >& 1 mean?

/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output. The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well.

What is Dev null for?

/dev/null in Linux is a null device file. This will discard anything written to it, and will return EOF on reading. This is a command-line hack that acts as a vacuum, that sucks anything thrown to it.

Why do we redirect to Dev null?

By combining redirection with the /dev/null device, we can silence error output, normal output, or both.

How do I view Dev null?

You write to /dev/null every time you use it in a command such as touch file 2> /dev/null. You read from /dev/null every time you empty an existing file using a command such as cat /dev/null > bigfile or just > bigfile. Because of the file's nature, you can't change it in any way; you can only use it.


1 Answers

If $PROG is a program that expects input from stdin, your script might stall forever waiting for you to type something in. The use of < /dev/null is to provide an empty input to such a program. You're right about the > and 2>&1.

This snippet of script is checking to see if $PROG --version exits with a 0 status (success), and then runs that program without any flags. If $PROG --version fails, the script echoes "failed" and exits.

like image 198
Carl Norum Avatar answered Sep 30 '22 20:09

Carl Norum