Linux Shell Scripting Tutorial Part 1 - File Operators

This is Part 1 of Linux Shell Tutorials Series, in this tutorial we will learn file operators that are commonly used in shell scripts.

For executing these scripts provide filenames as script arguments.

Linux shell script to check if file exist

  #!/bin/bash

  if test -e $1 ; then
          echo "$1 file exist"
          cat $1
  else
          echo "$1 file does not exist"
  fi


How to check if file exists and not file is not empty

  #!/bin/bash

  if test -s $1;then
          echo "file exist and file is not empty"
  else
          echo "file is either empty or not exist"
  fi


Check if file1 is newer than file2

  #!/bin/bash

  if test $1 -nt $2;then
          echo "$1 is newer than $2 according to modification time"
  else
          echo "$1 is older  than $2 according to modification time"
  fi


Check if file1 is older than file2

  #!/bin/bash

  if test $1 -ot $2; then
          echo "$1 is older than $2"
  fi


Check if file is a directory


#!/bin/bash

if test -d $1;then
        echo "$1 is  a directory"
fi



Follow US on Twitter: