9

I try to do the script:

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
    echo "Host found"
else
    echo "Host not found"
fi

and i turn it:

pi@raspberrypi ~ $ sh /home/pi/sh/test.sh

/home/pi/sh/test.sh: 9: /home/pi/sh/test.sh: Syntax error: "fi" unexpected (expecting "then")

where is the problem?

Jahid
  • 21,542
  • 10
  • 90
  • 108
Kwiatkowski
  • 519
  • 2
  • 7
  • 11
  • 1
    Sorry, I can not reproduce this problem with sh, bash and dash. – Cyrus May 04 '15 at 18:51
  • 1
    As written that shell script is syntactically valid. Are you sure that's the **exact** script you tested with? Copy and paste from here into a new file and run that. Does it work? – Etan Reisner May 04 '15 at 18:52
  • 1
    Crossposting: http://askubuntu.com/questions/618260/script-sh-syntax-error – Cyrus May 04 '15 at 19:00
  • 2
    It's probable that your script has DOS line endings. Saving your script gives me a similar syntax error in `dash` (although it's an unexpected end-of-file rather than unexpected "fi"). You might have mixed line endings; see http://stackoverflow.com/q/3773649/1126841. – chepner May 04 '15 at 19:06
  • Possible duplicate of [Bash syntax error: unexpected end of file](https://stackoverflow.com/questions/6366530/bash-syntax-error-unexpected-end-of-file) – Jo Ham Nov 30 '18 at 16:45

5 Answers5

15

You can try

$ dos2unix /home/pi/sh/test.sh

and run it again.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • also when you trying to build some posix project from github under cygwin it is good idea to clone from git it also under cygwin – Mirek Michalak Jan 20 '17 at 19:42
7

Most probably this is because carriage-return \r in your script. Try run this command to clean-up your script. Just run once. Original file will be backed up.

perl -pi.bak -e 's/\r$//' /home/pi/sh/test.sh
tivn
  • 1,883
  • 14
  • 14
3

If you are editing the script file with Notepad++ on windows you can convert the EOL from the program menu with

Edit => EOL Conversion => Unix (LF)
Andrea Mauro
  • 773
  • 1
  • 8
  • 14
  • 1
    Solved my issue. My line endings was affected when taking out git repo anew and 'Syntax error: "fi" unexpected (expecting "then")' was the only clue to what had changed since it worked. Quite hard to sort out from message! – Henrik Feb 04 '21 at 21:25
3
if xxx then
  commond
fi

Syntax error: “fi” unexpected (expecting “then”)

try it :

if xxx 
then
  commond
fi

it's ok.

SHR
  • 7,940
  • 9
  • 38
  • 57
0

It may be that you saved to the file from an ftp server rather than via nano or other console file edit prog.

Try pasting the code into the (empty) file via nano.

This fixed that exact issue for me.