0

I'm trying to create script where user will give path to some file, and script will check if file exists and do some stuff... I've wrote this code:

read -p "Enter path: " $path

#check if path is not empty string
if [ -z $path ]
then
  echo "path is empty string"
  exit
fi
#check if file exist
if [ ! -f $path ] 
then
  echo "file doesnt exists"
fi

my problem is with secound condition - if I change $path with some string everything is OK, but when I enter path via variable it is always "file doesnt exists" I was trying with

if [ ! -f `$path` ]

but if file doesnt have execute permission result is fail too. Can someone help me fix above code? :)

EDIT sorry, I meant -z and -f not double -z condition

  • 1
    You're using the -z test twice, you might want -e to check if the file exists in the second test condition? – HBruijn Nov 8 '13 at 11:29
  • yeah, -e was correct, I was trying with -f but if file was without execute permission i get error. – Krystian Nov 8 '13 at 11:35
2

The problem here is that the backticks:

`command`

are used to run a command and substitute its output streams (standard and error) as a result, which is why the test fails when you supply a file without execute permissions.

How to fix this

Use

if [ -f "$path" ]

The double quotes are to protect against word splitting (in case the contains spaces) and against globbing (in case the path contains wildcard characters like * or ?)

Even better, since the path may be to a directory, simply check for the existence of the path with -e:

if [ -e "$path" ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.