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
  • 98,183
  • 15
  • 197
  • 293
Prachi
  • 87
  • 1
  • 8
  • 1
    `if [ -f $fname ];` is spaces are missing? – snoop Oct 19 '15 at 09:18
  • 1
    See [Differences between doublequotes “ ”, singlequotes ' ' and backticks ´ ´ on commandline?](http://askubuntu.com/questions/20034/differences-between-doublequotes-singlequotes-and-backticks-%c2%b4-%c2%b4-on-comm) for detailed background regarding quoting in shell. – Volker Siegel Oct 19 '15 at 10:10

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
  • 9,909
  • 1
  • 23
  • 41
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
  • 293,910
  • 41
  • 570
  • 710
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,124
  • 39
  • 95
  • 141