Check if file exists and whether it contains a specific string

randeepsp picture randeepsp · Sep 22, 2010 · Viewed 126.8k times · Source

I want to check if file2.sh exists and also if a specific word, poet is part of the file. I use grep to create the variable used_var.

#!/bin/ksh

file_name=/home/file2.sh                  
used_var=`grep "poet" $file_name`    

How can I check if used_var has some value?

Answer

dogbane picture dogbane · Sep 22, 2010

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

============

Here are some commonly used tests:

   -d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi