sagar reddy sagar reddy - 2 months ago 19
Bash Question

pattern matching in sudoers file using tab space in pattern

I need to write a shell script to check the entry is there or not in /etc/sudoers file

this is the pattern i need to check
nimbus ALL=(ALL) NOPASSWD:ALL

in this pattern word to word tab space is there

how to find the pattern exist in file /etc/sudoers or not using linux shell script from root user only

please help me in this regard

thanks
sagar

Answer

The problem with your script is, you are not escaping(\) the meta-characters(( and ) in this case) for grep to identify them as they have a special meaning.

Also quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.

The modified version of your script should be like

#!/bin/bash

SomeString='nimbus      ALL=\(ALL\)       NOPASSWD:ALL'      # Notice the '\' of the characters
File=sudoers
echo "$File"
echo -e "$SomeString"

if grep -qE "$SomeString" "$File"; then
    echo "line found"
else
    echo "line not found"
fi

With this change your script works.

$ cat sudoers
nimbus      ALL=(ALL)       NOPASSWD:ALL
foo
bar

foobar

$ ./script.sh
sudoers
nimbus      ALL=\(ALL\)       NOPASSWD:ALL
line found

Read more about grep-regular-expressions