Kwiatkowski
Kwiatkowski

Reputation: 569

Syntax error: "fi" unexpected (expecting "then") in bash script

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?

Upvotes: 13

Views: 26838

Answers (6)

Quaresma
Quaresma

Reputation: 21

In my case the problem was CRLF instead LF. I just changed the option in VSCode and ran it again. In VSCode I changed it by clicking on the option shown below:

VSCode LF option location

Upvotes: 2

Programmer IPls
Programmer IPls

Reputation: 9

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.

Upvotes: 0

Dongsheng Zhao
Dongsheng Zhao

Reputation: 31

if xxx then
  commond
fi

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

try it :

if xxx 
then
  commond
fi

it's ok.

Upvotes: 3

Andrea Mauro
Andrea Mauro

Reputation: 842

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)

Upvotes: 3

Diego Torres Milano
Diego Torres Milano

Reputation: 69368

You can try

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

and run it again.

Upvotes: 17

tivn
tivn

Reputation: 1923

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

Upvotes: 8

Related Questions