0

I want to check if file exists and then check for a substring in the file

if [ -f /etc/abc.conf ]; then
   if [ grep 'abc.conf' -e 'host.com' ]
    test = 'PASS'
   else 
    test = 'FAIL'
   fi
else
   echo "File doesnot exist"
fi

echo $test

Please let me know if there is a better way to do the same

meallhour
  • 13,921
  • 21
  • 60
  • 117

2 Answers2

2

Yes, your grep might support the -s argument:

   -s, --no-messages
          Suppress error messages about nonexistent or unreadable files.

So something like this should work:

grep -qs 'abc.conf' '/etc/abc.conf' && test='PASS' || test='FAIL'
steffen
  • 16,138
  • 4
  • 42
  • 81
1

Grep returns 2 if file does not exist or is not readable, and 1 if the string is not found.

grep -qs '<string>' file.txt
res=$?
if [ $res -eq 0 ]; then
  test='PASS'
elif [ $res -eq 1 ]; then
  test='FAIL'
elif [ $res -eq 2 ]; then
  echo "Cannot read file"
else
  echo "Unrecognized return code ($res) from grep"
fi
Jack
  • 5,801
  • 1
  • 15
  • 20