LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   dev/null (https://www.linuxquestions.org/questions/linux-newbie-8/dev-null-4175545934/)

nbonda 06-20-2015 08:37 AM

dev/null
 
I am learning shell scripting. I came across "> /dev/null" many times, As a beginner I know that means "redirecting output to trash. WHAT IS THE SIGNIFICANCE OF IT IN BELOW SCRIPT?.
example code:

while read ip name
do
echo $ip | grep "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" > /dev/null
if [ "$?" -eq "0" ]; then
echo "$name is at $ip"
fi
done < /etc/hosts

wpeckham 06-20-2015 08:49 AM

/dev/null
 
Used as it is in that script, it hides the STDOUT of the grep command. The if does not require STDOUT, only the return value. Sending the output to null keeps the output clean instead of sending the output of the grep to stdout on a terminal, into cron email, a log file, or some output that then becomes cluttered.

IT is a tool of the good scripter acting as butler: keeping things neat and tidy.

Incidently, the script is flawed. There are several possible ways to fix it, but it does not take into consideration that many hosts entries contain aliases, comments, and other verbiage after the name. There are also comment lines that should be ignored entirely for correctness, though they are unlikley to cause this snip to misbehave. It would also need significant editing to take IPv6 into account.

Was this from a textbook or classroom example?

twork 06-20-2015 10:07 AM

Quote:

Originally Posted by nbonda (Post 5380281)
I am learning shell scripting. I came across "> /dev/null" many times, As a beginner I know that means "redirecting output to trash.

As a beginner, do you also know the difference between "output" and "return code" or "exit status"? I didn't when I was new, so just in case:

Typically, output is written to the controlling terminal. (The user's own shell in this case.) You're probably used to using grep for its output: take whatever came in, apply the filter, and show us what the filter doesn't remove.

The exit status, or return code, is a number that's sent to the controlling process when a program ends. Typically, a value of "0" means that the program ended successfully, and some other number means there was some kind of error, or otherwise "not typical" exit status. Usually when we use the shell, we don't see the exit status, especially if everything is going according to plan.

Typically, the exit status isn't what we use grep for. It's a filter, and we're interested in its output. But when grep doesn't let anything through at all, that's considered an error, so the exit status is set to "1", and that can be useful sometimes, as in your case.


All times are GMT -5. The time now is 12:37 AM.