bash 语法错误:“fi”意外

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26915539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:47:19  来源:igfitidea点击:

Syntax error: "fi" unexpected

bashshellsyntax-error

提问by mee

I am trying to write a shell script that will either start or stop openvpn, depending on what the user enters. When I run the script it correctly prompts me for what I want to do. But when I type "1" and hit [Enter] it outputs this and terminates:

我正在尝试编写一个 shell 脚本,该脚本将根据用户输入的内容启动或停止 openvpn。当我运行脚本时,它会正确提示我想要做什么。但是当我输入“1”并点击[Enter]时,它会输出这个并终止:

./control-openvpn.sh: 27: ./control-openvpn.sh: Syntax error: "fi" unexpected

Here is the main part of my code. The functions are above it in the script.

这是我的代码的主要部分。函数在脚本中位于其上方。

# Main
echo -n "What to do? 1.Start or 2.Stop. [1/2]"
read action
if [ "$action" == "1" ]
then
    start_openvpn()
elif [ "$action" == "2" ]
then
    stop_openvpn()
fi

Thank you in advance

先感谢您

采纳答案by Jason Colyer

In bash, when you do start_openvpn(), you are declaring a new function. Thus, bash gets confused when the next thing it sees is fi. Something like this should work for you:

在 bash 中,当您执行 start_openvpn() 时,您是在声明一个新函数。因此,当 bash 看到的下一件事是 fi 时,它会感到困惑。像这样的事情应该适合你:

read -p 'What to do? 1.Start or 2.Stop. [1/2] ' action
if [ $action -eq 1 ]; then
    start_openvpn
elif [ $action -eq 2 ]; then
    stop_openvpn
fi