Following script describes how you can check if a file exists or not. The script takes a filename as the argument and displays if the file exists or not. The script also checks for correct number of arguments passed to it.


  • Let's check whether the user has passed the correct number of arguments or not. $# is special shell script variable which tells the number of arguments passed to the current script. If number of arguments is not equal to 1, show an error and exit out of the script.

    if [ $# -ne 1 ]

    then
  • Display the error message and exit with 1 value i.e. failure. $0 is the special shell script variable which contains the 0th string value taken from the prompt i.e. shell script name in our case.

    echo "Usage - $0 file-name"

    exit 1

    fi
  • Here we are checking if the file exists or not. -f is used in the if condition which is used for checking if a file is a normal file. The if condition will return 1 if -f returns true i.e. if the file exists, otherwise it will return false i.e. file does not exists.

    if [ -f $1 ]

    then

    echo "$1 file exist"

    else

    echo "Sorry, $1 file does not exist"

    fi