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

16,290

Solution 1

You can try

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

and run it again.

Solution 2

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

Solution 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)

Solution 4

if xxx then
  commond
fi

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

try it :

if xxx 
then
  commond
fi

it's ok.

Share:
16,290
Kwiatkowski
Author by

Kwiatkowski

Updated on July 22, 2022

Comments

  • Kwiatkowski
    Kwiatkowski almost 2 years

    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?