| || |
Join Date: Jun 2008
How to Check File Exists or Not in Linux
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 ]
- 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"
- 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 ]
echo "$1 file exist"
echo "Sorry, $1 file does not exist"