Difference between revisions of "/dev/null discards unwanted output"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
(Created page with ' Category:Redirection')
 
Line 1: Line 1:
 +
All data written on a /dev/null or /dev/zero special file is discarded by the system. Use /dev/null to send any unwanted output from program/command and syntax is:
 +
<pre>command >/dev/null</pre>
 +
OR
 +
<pre>command 2>/dev/null</pre>
 +
The last syntax redirects the the command error to /dev/null where it is ignored by the shell.
 +
==Example==
 +
Consider the following example from [[the exit status]] chapter. The output of '''grep "^$username" $PASSWD_FILE > /dev/null''' is send to /dev/null where it is ignored by the shell.
 +
<source lang="bash">#!/bin/bash
 +
# set var
 +
PASSWD_FILE=/etc/passwd
  
 +
# get user name
 +
read -p "Enter a user name : " username
 +
 +
# try to locate username in in /etc/passwd
 +
#
 +
grep "^$username" $PASSWD_FILE > /dev/null
 +
 +
# store exit status of grep
 +
# if found grep will return 0 exit stauts
 +
# if not found, grep will return a nonzero exit stauts
 +
status=$?
 +
 +
if test $status -eq 0
 +
then
 +
echo "User '$username' found in $PASSWD_FILE file."
 +
else
 +
echo "User '$username' not found in $PASSWD_FILE file."
 +
fi</source>
 
[[Category:Redirection]]
 
[[Category:Redirection]]

Revision as of 11:48, 17 September 2009

All data written on a /dev/null or /dev/zero special file is discarded by the system. Use /dev/null to send any unwanted output from program/command and syntax is:

command >/dev/null

OR

command 2>/dev/null

The last syntax redirects the the command error to /dev/null where it is ignored by the shell.

Example

Consider the following example from the exit status chapter. The output of grep "^$username" $PASSWD_FILE > /dev/null is send to /dev/null where it is ignored by the shell.

#!/bin/bash
# set var 
PASSWD_FILE=/etc/passwd

# get user name
read -p "Enter a user name : " username

# try to locate username in in /etc/passwd 
# 
grep "^$username" $PASSWD_FILE > /dev/null

# store exit status of grep
# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts
status=$?

if test $status -eq 0
then
	echo "User '$username' found in $PASSWD_FILE file."
else
	echo "User '$username' not found in $PASSWD_FILE file."
fi