Shell Programming - File Operators

Unix

In this tutorial we will learn about file operators in Shell Programming.

We will be using the if statement to perform tests.

And we will be using a variable file to store the file name and we have set the read, write and execute permission.

Note! To change the file permission use the following command.

$ chmod 755 filename

Or, use chmod 777 filename if you want to give access to everyone.

Example:

In the following example we are setting the permission of helloworld.txt file.

$ chmod 755 helloworld.txt

File operators

OperatorNote
-eTo check if the file exists.
-rTo check if the file is readable.
-wTo check if the file is writable.
-xTo check if the file is executable.
-sTo check if the file size is greater than 0.
-dTo check if the file is a directory.

Example #1: Write a Shell Script to check if a file exists

In the following example we are going to check if helloworld.txt exists.

#!/bin/sh

file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file/helloworld.txt"

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

Output:

$ sh example01.sh 
File exists!

Example #2: Write a Shell Script to check a directory

#!/bin/sh

file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file"

# check
if [ -d $file ]
then
  echo "Directory exists!"
else
  echo "Directory does not exists!"
fi

Output:

$ sh example02.sh 
Directory exists!

Example #3: Write a Shell Script to check if a file is readable, writable and executable

#!/bin/sh

file="/Users/yusufshakeel/Documents/GitHub/shell-script/example/file/helloworld.txt"

# check
if [ -e $file ]
then
  echo "File exists!"

  # check readable
  if [ -r $file ]
  then
    echo "File is readable."
  else
  	echo "File is not readable."
  fi

  # check writable
  if [ -w $file ]
  then
    echo "File is writable."
  else
  	echo "File is not writable."
  fi

  # check executable
  if [ -x $file ]
  then
    echo "File is executable."
  else
  	echo "File is not executable."
  fi

else
  echo "File does not exists!"
fi

Output:

$ sh example03.sh 
File exists!
File is readable.
File is writable.
File is executable.