-1

I wanted to check if a file contains a string in bash. I have done so for regular string characters. However, i need to check a new string which contains double quote ".

Say the string is:

PARAMETER_XYZ="no"

I tried this, but does not work:

ABC=$(cat /etc/file)
if [[ $ABC = *"PARAMETER_XYZ=\"no\""*]] ; then
   exit 0
fi

Any suggestions?

drdot
  • 3,215
  • 9
  • 46
  • 81
  • 1
    Use `grep -Fq 'PARAMETER_XYZ="no"' /etc/file` – anubhava Oct 05 '18 at 21:40
  • Possible duplicate of [How to check a string if it contains a special character (!@#$%^&\*()\_+)](https://stackoverflow.com/q/26621736/608639) – jww Oct 06 '18 at 08:35

1 Answers1

1

grep is the program of choice to look for the presence of strings.

if grep 'PARAMETER_XYZ="no"' /etc/file > /dev/null then
   exit 0
fi

You can also still do it with [[ if you really want:

ABC=$(cat /etc/file)
if [[ $ABC = *'PARAMETER_XYZ="no"'* ]] ; then
   exit 0
fi

However, if that's actually a config file you're trying to parse, there are better solutions that are less fragile than looking for an exact string. That file looks like it might even be a shell variables file, in which case you could just source it and then check $PARAMETER_XYZ directly.

  • It is a config file. What would be a better solution? – drdot Oct 05 '18 at 21:39
  • Depends on the format. If all of the lines look like that, and you trust it, you could `source` it and then just see if $PARAMETER_XYZ equals "no". – Joseph Sible-Reinstate Monica Oct 05 '18 at 21:40
  • Yes, all the lines looks like this except some others lines starts with # as comments. Could you add this method to your answer? I will take this. Thank you! – drdot Oct 05 '18 at 21:41
  • Just one more question, if I source it, these parameters stays in my shell environment. Would that have undesirable effects? – drdot Oct 05 '18 at 21:46
  • It depends exactly what they're called, but you could do the source and checking in a subshell to avoid the problem, since subshells lose their variables when they end. – Joseph Sible-Reinstate Monica Oct 05 '18 at 21:47
  • Actually, if I source, then none of the shell script after source get executed. Could you show me how to check the variables after sourcing them in a subshell? I asked the question here https://stackoverflow.com/questions/52673779/how-to-check-environment-variable-in-a-linux-subshell – drdot Oct 05 '18 at 22:04
  • i am still debugging. it may be due to other reasons. – drdot Oct 05 '18 at 22:24