#!/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.
#!/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.
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.
Surround filename with quotes:
if [ -f "$fileName" ]; then
You must use the quotes in the if
as well:
if [ -f "$fileName" ]; then
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
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.
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
.