3

My code of shell script is as follows:

echo "Enter file name";
read fname;
if [-f$fname];
then
    echo "File already exists";
fi`

However, when I run my script, I get this error:

[-ffile]: not found

I have tried spacing -f $fname but I still get the same error. Why is this happening and how can I fix it?

terdon
  • 100,812
Prachi
  • 87
  • 1
  • 8

3 Answers3

8

You may have added a value that contains a space. To prevent this, always quote your variables:

if [ -f "$fname" ]

Also, note that [ and ] need a space around. Why? Because [ is a command, so it must be separated by a white space from the preceding statement. You can read about it by typing man test.

All together:

echo "Enter file name";
read -r fname;
if [ -f "$fname" ]; then
   echo "File already exists";
fi

See a test on how quotes matter:

$ touch "a b"
$ filename="a b"
$ [ -f $filename ] && echo "exists!"
bash: [: a: binary operator expected
$ [ -f "$filename" ] && echo "exists!"
exists!
fedorqui
  • 10,069
4

I would expect -e "$fname" or if [[ -e $fname ]] (the last one is not universal across shells).

So

echo "Enter file name"; read fname; if [ -e "$fname" ]; then echo "File already exists"; fi

In any case and to make sure: always use quotes ;)

Rinzwind
  • 299,756
0

Here's what the script should look like

echo "Enter file name";
read fname;
if [ -f "$fname" ];
then 
  echo "File already exists";
fi

You need space around the brackets and should quote the variable.

TellMeWhy
  • 17,484