Unix - Shell File Test Operators Example

Advertisements


Here is an example which uses all the file test operators:

Assume a variable file holds an existing file name "/var/www/tutorialspoint/unix/test.sh" whose size is 100 bytes and has read, write and execute permission on:

#!/bin/sh

file="/var/www/tutorialspoint/unix/test.sh"

if [ -r $file ]
then
   echo "File has read access"
else
   echo "File does not have read access"
fi

if [ -w $file ]
then
   echo "File has write permission"
else
   echo "File does not have write permission"
fi

if [ -x $file ]
then
   echo "File has execute permission"
else
   echo "File does not have execute permission"
fi

if [ -f $file ]
then
   echo "File is an ordinary file"
else
   echo "This is sepcial file"
fi

if [ -d $file ]
then
   echo "File is a directory"
else
   echo "This is not a directory"
fi

if [ -s $file ]
then
   echo "File size is zero"
else
   echo "File size is not zero"
fi

if [ -e $file ]
then
   echo "File exists"
else
   echo "File does not exist"
fi

This would produce following result:

File has read access
File has write permission
File has execute permission
File is an ordinary file
This is not a directory
File size is zero
File exists

There are following points to note down:

  • There must be spaces between operators and expressions for example 2+2 is not correct, where as it should be written as 2 + 2.

  • if...then...else...fi statement is a decision making statement which has been explained in next chapter.



Advertisements
Advertisements