首页 > 解决方案 > Bash 语法问题,'语法错误:意外的“do”(期待“fi”)'

问题描述

我有一个在 Windows 和 Mac/Linux 机器上使用的 sh 脚本,并且似乎可以正常工作。

#!/bin/bash
if [ -z "$jmxname" ]
then
cd ./tests/Performance/JMX/ || exit

echo "-- JMX LIST --"

# set the prompt used by select, replacing "#?"
PS3="Use number to select a file or 'stop' to cancel: "

# allow the user to choose a file
select jmxname in *.jmx
do
    # leave the loop if the user says 'stop'
    if [[ "$REPLY" == stop ]]; then break; fi

    # complain if no file was selected, and loop to ask again
    if [[ "$jmxname" == "" ]]
    then
        echo "'$REPLY' is not a valid number"
        continue
    fi

    # now we can use the selected file, trying to get it to run the shell script
    rm -rf ../../Performance/results/* && cd ../jmeter/bin/ && java -jar ApacheJMeter.jar -Jjmeter.save.saveservice.output_format=csv -n -t ../../JMX/"$jmxname" -l ../../results/"$jmxname"-reslut.jtl -e -o ../../results/HTML
    # it'll ask for another unless we leave the loop
    break
done
else
    cd ./tests/Performance/JMX/ && rm -rf ../../Performance/results/* && cd ../jmeter/bin/ && java -jar ApacheJMeter.jar -Jjmeter.save.saveservice.output_format=csv -n -t ../../JMX/"$jmxname" -l ../../results/"$jmxname"-reslut.jtl -e -o ../../results/HTML
fi

我现在正在尝试使用 Docker 容器做一些事情,并使用了 node:alpine 映像,因为我的项目的其余部分是基于 NodeJS 的,但由于某种原因,该脚本不会在 Docker 容器中运行,给出以下内容 -

line 12: syntax error: unexpected "do" (expecting "fi")

我该如何解决?该脚本似乎适用于迄今为止运行的每个系统,并且没有引发任何问题。

标签: node.jsbashshelldockersh

解决方案


错误消息表明该脚本作为“/bin/sh”执行,而不是作为/bin/bash。您可以使用“/bin/sh -n script.sh”查看消息

检查脚本是如何被调用的。在不同的系统上,/bin/sh 符号链接到 bash 或其他功能较少的 shell。

特别是,问题在于select包含在 bash 中但不是 POSIX 标准的一部分的语句。

另一种选择是 docker 上的 bash 默认设置为 POSIX 兼容


推荐阅读