Tag Archives: Function realization

Solve the problem of shell script “syntax error near unexpected token `fi'”.

Start by listing my shell script.
I edit it in the Windows editor and then upload it to Linux for execution.

#!/bin/bash
Monitor()
{
	pgrep -x mysqld &> /dev/null
	if [ $?-ne 0 ];
	then
		echo "At time: `date` :MySQL is stop .">> /opt/service/logs/mysqlMonitor.log
		/sbin/service mysqld start
	else
		echo "MySQL server is running ."
	fi
	echo "-----------------------------------"
}
Monitor

This error has been reported since Linux was executed.
mysqlmonitor.sh: line 9: syntax error near unexpected token `fi’
mysqlmonitor.sh: line 9: `fi’
At the beginning, I thought the Linux command was wrong. I looked up a lot of information. It was a simple statement, and I was sure it was right. But why report such an error?
I took the cat-v mysqlmonitor.sh command to see my code

Monitor()^M
{^M
        pgrep -x mysqld &> /dev/null^M
        if [ $?-ne 0 ];then^M
                echo "At time: `date` :MySQLM-BM- is stop .">> /opt/service/logs/mysqlMonitor.log^M
                /sbin/service mysqld start^M
        else^M
                echo "MySQL server is running ."^M
        fi^M
        echo "-----------------------------------"^M
}^M
Monitor^M

Found in Linux after the automatic view in the end of the line with ^M identity, through looking up the information that in Windows and Linux is not the same newline. The details can also be confirmed by the command again.
Open the file with Vim and type in command line mode

What we found was DOS

Now set our code mode with the command: set FF = Unix

And then save the code


Look again and discover that the code is programmed for Unix
Cat -v **.sh to see that the code is normal.
There are no errors in executing the code again.
If you think it’s working, check out this article below. You can also consult me through QQ: 772757263