views:

281

answers:

6
#!/bin/bash -x

echo "Enter file name: "
read fileName
fileName=`pwd`"/$fileName"
if [ -f $fileName ]; then
    echo "file is present"
fi

Even if I change the value of fileName by adding quotes at starting and end.. The script still doesnt work.

+3  A: 

Wrapping it in double-quotes works for me:

#!/bin/bash -x

echo "Enter file name: "
read fileName
fileName=`pwd`"/$fileName"
if [ -f "$fileName" ]; then
        echo "file is present"
fi

I believe this will take care of most special characters, including quotes themselves.

Mark Biek
Why the downvote?
Mark Biek
:omg: it was that easy.. thanx.
shadyabhi
+1  A: 

Surround filename with quotes:

if [ -f "$fileName" ]; then
R Samuel Klatchko
+4  A: 

You must use the quotes in the if as well:

if [ -f "$fileName" ]; then
zneak
+2  A: 

You can quote the filename when you do the -f test. Try this instead

#!/bin/bash -x
echo "Enter file name: "
read fileName
fileName=`pwd`/$fileName
if [ -f "$fileName" ]; then
    echo "file is present"
fi
Suresh Krishnan
+3  A: 

Change if [ -f $fileName ]; then to if -f "$fileName" ];. Otherwise when the file contains a space the -f operation will be passed more than one argument. If you passed in a file named "this file", the shell will expand it to:

if [ -f this file ]; then

causing the error.

Matt McClellan
+2  A: 

You're prepending the pwd even if the user entered an absolute path. Try this:

case "$fileName" in
    /*) ;; # okay
    *)  fileName=`pwd`/"$fileName"
esac

This will only prepend the pwd if fileName doesn't start with a /.

Also, your if test will only succeed if fileName is a regular file. If you want it to succeed for directories and the like, test with -e instead of -f.

Kenster
+1 for answering the next question that might get asked.
Matt McClellan