使用正确的语法运行Bash脚本但它一直给我一个语法错误

时间:2016-08-11 20:45:37

标签: bash shell server syntax-error application-restart

我一直在尝试编译我的Bash脚本,但即使我遵循正确的语法,我仍然会收到此语法错误。

代码:

    #!/bin/sh
set -u
SERVICE_NAME=Server
PATH_TO_JAR=/usr/local/MyProject/MyJar.jar
PID_PATH_NAME=/tmp/Server-pid
case $1 in
    start)
        echo "Starting $SERVICE_NAME ..."
        if [ ! -f "$PID_PATH_NAME" ]; then
             nohup java -cp '/home/ubuntu/ResumeParser/ResumeParser/ResumeTransducerbin/* :/home/ubuntu/ResumeParser/ResumeParser/GATEFiles/lib/*:/home/ubuntu/.../ServerTest' /tmp 2>> /dev/null >> /dev/null &
                        echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is already running ..."
        fi
    ;;
    stop)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stoping ..."
            kill $PID;
            echo "$SERVICE_NAME stopped ..."
            rm $PID_PATH_NAME
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
    restart)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stopping ...";
            kill $PID;
            echo "$SERVICE_NAME stopped ...";
            rm $PID_PATH_NAME
            echo "$SERVICE_NAME starting ..."
            nohup java -cp '/home/ubuntu/ResumeParser/ResumeParser/ResumeTransducerbin/*:/home/ubuntu/... ServerTest' /tmp 2>> /dev/null >> /dev/null &
                        echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
esac
 

当我运行:sudo service Server start

    /etc/init.d/Server: 9: /etc/init.d/Server: Syntax error: "then" unexpected     (expecting ";;")

当我运行时:bash -n Server

Server: line 9: syntax error near unexpected token `then'
Server: line 9: `        if [ ! -f $PID_PATH_NAME ]; then'

我做错了什么?

3 个答案:

答案 0 :(得分:1)

不确定$PID_PATH_NAME的值 试试if [ ! -f "$PID_PATH_NAME" ]; - >只是为了确保PID_PATH_NAME不添加额外的属性/字符。

但是我建议在shell / bash脚本上运行静态工具来找到像这样的疯狂/简单问题。

Static tool to verify shell scripts syntax

答案 1 :(得分:0)

崩溃可能发生PID_PATH_NAME为空/未定义或甚至包含空格

Shell将其视为if [ ! ]; then

体型

if [ ! -f "$PID_PATH_NAME" ]; then

此外,如果PID_PATH_NAME有机会为空,而不是获得奇怪的行为(测试是否存在空文件名始终为false),您可以在测试之前检查文件是否存在:

在这种情况下,我已经将它改编为你的参数解析,因为如果你没有向你的脚本传递任何参数,它会以一种不太用户友好的方式失败:

if [ -z "$1" ]; then
   echo "no command defined: should be start, restart, stop. Aborting"
   exit 1
fi

答案 2 :(得分:0)

你需要

$query = "SELECT * FROM t_product WHERE name LIKE $name AND price LIKE $price ";
在案例陈述之前