3
$!/bin/sh
if grep "$1" /etc/passwd 2>/dev/null               #Search username at beging of line1
then
         echo "Pattern found - Job Over"
else 
         echo "Pattern not found"

fi
Kusalananda
  • 333,661

2 Answers2

5

In bash, 1 means stdout, 2 means stderr(standard error stream)

/dev/null is a virtual device to which you can write anything, and it would consume everything(essentially getting rid of the output).

So, 2> /dev/null means that, redirect the error output from this command to /dev/null. Essentially meaning, just get rid of the error messages

Insaf K
  • 183
1

The intent with 2>/dev/null is to hide errors produced by grep by redirect any diagnostic messages to /dev/null (a special device file that discards the data written to it).

The /etc/passwd file is generally readable by all users, so I don't quite understand why redirecting the error stream is needed. However, since the code uses grep in an if statement, the output that the utility may produce (the lines matching $1) may be unwanted, and with >/dev/null this output would be discarded. I'm therefore proposing that the 2 in the code is a typo and the author intended to write

#!/bin/sh

if grep -e "$1" /etc/passwd >/dev/null; then
    echo "Pattern found - Job Over"
else 
    echo "Pattern not found"
fi

That is, to echo either string, while discarding the actual lines that matched. The -e is needed in case the string in $1 starts with a dash. Also note the corrected #!-line.

This could also be done without any redirection:

#!/bin/sh

if grep -q -e "$1" /etc/passwd; then
    echo "Pattern found - Job Over"
else 
    echo "Pattern not found"
fi

The -q makes grep quit as soon as a match is found, and also makes it quiet (it does not output the matched lines).


If this is to grep for a username in /etc/passwd, then using

if getent passwd "$1" >/dev/null; then ...; fi

would be a better option, as using a plain grep may find usernames that contains the string in $1 as substrings, unless you take care crafting the expression properly (the regular expression is not actually shown in the question). The getent passwd command would exit with a non-zero exit status if the given username was not found in the passwd database.

This would also work on systems using a NIS or LDAP database for storing user information, but would not work on macOS (no getent utility).

Kusalananda
  • 333,661