0

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?

  • 2
    if [ -z `sudo cat /etc/sudoers | grep "$USER ALL=(ALL) NOPASSWD:ALL"` ]; then echo "no out"; else echo "out"; fi works fine. – Spike Oct 3 '16 at 9:16
  • my ownly concern is the output if "bash: [: too many arguments", I receive my answer but why does the error occur? – Cybex Oct 3 '16 at 9:46
  • 1
    if [[ -z `sudo cat /etc/sudoers | grep "$USER ALL=(ALL) NOPASSWD:ALL"` ]]; then echo "no out"; else echo "out"; fi should be fine. – Spike Oct 3 '16 at 9:59
8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.