1

I am getting the error: ./Lab17Part3: line 4: [: missing `]' when I try to run this code. Oddly enough, it then continues to work as intended.

#!/bin/sh
    #Delete a file interactively
    filename=$1
    if [ !-f $filename && !-d $filename ]
    then
      echo "There is no file \"$filename\"."
    else
      echo "Do you want to delete \"$filename\"?"
      read choice
      if test $choice = y
      then
        if [ -d $filename ]
        then
          rmdir $filename
          echo \"$filename\" deleted
        else
          rm $filename
          echo \"$filename\" deleted
        fi
      else
        echo \"$filename\" not deleted.
      fi
    fi

Why am I getting the error, as my line for definitely has a ']' to terminate it. I don't think there are any other syntax things missing. I remembered to have a space before the ']'.

MegaZeroX
  • 235
  • 1
  • 9

1 Answers1

2

line 4 should be:

if [ ! -f "$filename" ] && [ ! -d "$filename" ]

[ is command in bash, better to say, it's alias for test command. It could be also written like

if test ! -f "$filename" && test ! -d "$filename"

Also please use double-quotes for enclosing variables. In case when $filename is '' (empty string), my first condition would be expanded this way

if [ ! -f  ] && [ ! -d  ]

and it would cause syntax error. When you use double quotes, it's ok:

if [ ! -f "" ] && [ ! -d "" ]
Vrata Blazek
  • 464
  • 3
  • 12