linux - bash 中的 "syntax error near unexpected token ` elif '"错误

标签 linux bash

我写了一个脚本,部分脚本如下:

#!/bin/bash

if [ "$1" == "this_script" ] then
      this_script --parameters
elif [ "$1" == "other_script" ] then
      other_script --parameters
else
      echo "missing argument"
fi

当我运行这个脚本时,我得到了错误,

syntax error near unexpected token `elif'
`elif [ "$1" == "SWDB" ] then'

1) 行尾有问题吗?我在 Windows 上用 Notepad++ 编写了脚本,但我在编辑到 UNIX/OSX 格式下启用了 EOL 转换。

2) 如果不是行尾,错误是什么?

我在 Redhat Linux 操作系统的 bash shell 中运行这个脚本。

最佳答案

if [ ... ] 之后和 then 之前需要一个分号,对于 elif 也是如此:

if [ "$1" == "this_script" ]; then
#                           ^
#                           here!
#                              v
elif [ "$1" == "other_script" ]; then

来自 Bash manual - 3.2.4.2 Conditional Constructs :

The syntax of the if command is:

if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘else alternate-consequents’ is present, and the final command in the final if or elif clause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

关于linux - bash 中的 "syntax error near unexpected token ` elif '"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37438081/

相关文章:

linux - Bash 脚本进程替换语法错误 : "(" unexpected

linux - 获取在 Linux 系统上使用的正确以太网接口(interface)

php - docker 1.9 : Adding --link target to a running nginx container

bash - 在 Bash 循环中递增变量

linux - 为什么 docker0 桥在带有法兰绒的 kubernetes 集群中出现?

linux - 执行 if...then...fi 时出现 Cygwin 错误 - Bash 脚本

linux - Bash 有颜色、粗体和带下划线的字符。为什么不是斜体?

bash - 通过键盘输入暂停脚本

php - 如何从浏览器的命令行中执行外部 PHP 脚本

c - Linux 守护进程 localhost 有效,但实际 IP 无效