-1

I am getting this error when I try to run my shell script:

ERROR: line 13: syntax error near unexpected token `fi'

The script is:

case $# in
0) echo Usage is: $0 filename [filename]
  exit;;
*);;
esac

for i in $*
do
   if test -f $i;
   then
      echo $i
      cat $i
   else
fi
done

Why am I getting an error?

  • 2
    paste your code in shellcheck.net and see errors – Rahul Aug 9 '16 at 12:55
  • 1
    @Rahul, good advice, though shellsheck is missing a few like echo -> printf, errors should go on stderr, should exit non-zero on error, cat < "$i" instead of cat $i... – Stéphane Chazelas Aug 9 '16 at 13:55
  • @StéphaneChazelas That's mostly the kind of issues that I think we can only infer based on context, and computers are, as we know, rather poor at establishing context... – a CVn Aug 9 '16 at 14:35
3

As schily already mentioned, a bash shell script (which this looks distinctly like) does not allow empty blocks between if and either else, elif or fi, or between else or elif and the corresponding fi. (This comes down to: each conditional must do something.)

You can either delete the else statement, or, if you want it for later, place a dummy command within the else block. For example, you could rewrite your script to read:

case $# in
0) echo Usage is: $0 filename [filename]
  exit;;
*);;
esac

for i in $*
do
   if test -f $i;
   then
      echo $i
      cat $i
   else
      true
   fi
done

(I also indented the fi to match the if. That's a matter of style, but I personally find it much easier to read that way.)

true has as its sole purpose to return a successful exit status, but it is a command, so this script will do nothing if the name in $i does not refer to a simple file (test -f).

1

Empty commands are not allowed, so simply remove the else line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.