views:

58

answers:

4
#!/bin/ksh               
file_name=/home/file2.sh                  
used_var=`grep "poet" $file_name`    

I want to check if file2.sh exists and also if used_var has some value or it has nothing.

+2  A: 

test -e will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.

Test can be written either as test -e or using []

[ -e "$file_name" ] && grep "poet" $file_name

Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.

In general terms you can test if a string is non-empty using [ "string" ] which will return 0 if non-empty and 1 if empty

Steve Weet
A: 

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi
joschi
+1  A: 
if test -e "$file_name";then
 ...
fi

if grep -q "poet" $file_name; then
  ..
fi
+1  A: 

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can just check the return status of grep. Grep returns 0 if the pattern was found, non-zero otherwise.

grep "poet" $file_name > /dev/null
if [ $? -eq 0 ]
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
dogbane