Checking if string exists in file with cat | grep
grep
can be used as a condition command. It returns true when the pattern matches. Here, you want a fixed-string search (-F
) and probably to match on the full line (-x
):
if sudo cat /etc/sudoers |
grep -xqFe "$USER ALL=(ALL) NOPASSWD:ALL"
then
echo found
else
echo not found
fi
Or if the sudoers
configuration allows you to run the grep
command in addition to the cat
one:
if sudo grep -xqFe "$USER ALL=(ALL) NOPASSWD:ALL" /etc/sudoers
then
echo found
else
echo not found
fi
-q
tells grep
to be quiet, to just return the true/false status via the exit status but not output anything on stdout.
Note the sudoers configuration can include other configuration files which that approach will not take into account. Same for permissions granted to groups that the user is member of.
You may want to use sudo -lU "$USER"
instead.
Related videos on Youtube
CybeX
Updated on September 18, 2022Comments
-
CybeX over 1 year
Good day all
Purpose: checking if a string exists in a file and running actions accordingly
if [ -z 'sudo cat /etc/sudoers | grep "$USER ALL=(ALL) NOPASSWD:ALL"' ]; echo "no output, cont." || echo "line exists, skipping"
The output always presents "line exists, skipping" in bot cases where the line exists and does not.
Adding the output into a variable e.g. x, substituting the line in the if statement with the variable produces the correct output,
How may I 'skip' the variable route and run the command directly?
-
Spike over 7 years
if [ -z `sudo cat /etc/sudoers | grep "$USER ALL=(ALL) NOPASSWD:ALL"` ]; then echo "no out"; else echo "out"; fi
works fine. -
CybeX over 7 yearsmy ownly concern is the output if "bash: [: too many arguments", I receive my answer but why does the error occur?
-
Spike over 7 years
if [[ -z `sudo cat /etc/sudoers | grep "$USER ALL=(ALL) NOPASSWD:ALL"` ]]; then echo "no out"; else echo "out"; fi
should be fine.
-