Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 19-12-2008
Member
 
Join Date: Jun 2008
Posts: 144
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 ]

    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
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: , ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "How to Check File Exists or Not in Linux"
Thread Thread Starter Forum Replies Last Post
Unix: Check if a file exists with certain prefix Gracious Software Development 4 29-05-2010 06:01 PM
Check if URL exists (Java) Kelvin Little Software Development 7 08-01-2010 04:04 PM
How to check if file exists in directory with Php Zool Software Development 3 03-11-2009 12:36 PM
How to check if variable exists in C# Hamlet Software Development 3 28-08-2009 07:30 PM
C++ code to check or search if a file exists or not? RadhaV Software Development 4 17-02-2009 11:33 PM


All times are GMT +5.5. The time now is 10:51 PM.