I am trying to check for the existence of a file using the 'test' and the file existence options.
When trying to check for a file with a space in between e.g 'Team List', it gives the following error.
learn1: line 3: test: `Team: binary operator expected
I am pasting my code below as well:
echo "Please enter a file name"
read fname
if test -f $fname
then
echo "$fname exists"
else
echo "$fname doesnot exist"
fi
Space is one of the default input field seperators.
So, if you just use $fname then that's 2 arguments for test and hence doesn't work.
"$fname" is just 1 argument.
If you consider that the test command is looking for a single argument, and then you provide it with a list, then it will only test the first item in that list.
So, I created a test script named "test.ksh". Here it is:
#! /usr/bin/ksh
echo "enter a file name: \c"
read filename
if test -f "${filename}"; then
echo "Success: ${filename}"
else
echo "Failure: ${filename}"
fi
I also created a file in the same directory named "one two.txt".
�ls
one two.txt test.ksh
�test.ksh
enter a file name: one two.txt
Success: one two.txt
Then I changed test.ksh to remove the double quotes around the variable "filename":
#! /usr/bin/ksh
echo "enter a file name: \c"
read filename
if test -f ${filename}; then
echo "Success: ${filename}"
else
echo "Failure: ${filename}"
fi
I ran this in an identical manner as before:
�test.ksh
enter a file name: one two.txt
Failure: one two.txt
I believe that this is due to the way that the test function works. When presented with a list of words separated by spaces, it tests the first item in that list (in this case, part of a filename), but if that list of words is surrounded by double quotes, then it is viewed as a single argument, and the test is then successful.
Not entirely, the program "test" doesn't see the quotes in this case, it is the shell that splits the words into separate arguments. The program "test" gets the arguments as an already separated list in it's main(argc,argv)