linux - elif 的语法错误

标签 linux bash scripting

<分区>

我编写了一个使用 if - elif 结构的小脚本。由于某种原因,它只是行不通。 错误代码:

./lab4.sh: line 9: syntax error near unexpected token `elif'
./lab4.sh: line 9: `elif [ $number -eq 2 ] then func2'

我的实际代码:

#!/bin/bash
#ask the user for a number between 1 and 3
#create some functions, write out the function number
echo "Enter a number between 1 and 3: "
read number

#which function should be called?
if [ $number -eq 1 ] then func1
elif [ $number -eq 2 ] then func2
elif [ $number -eq 3 ] then func3 fi

function func1 {
    echo "This message was displayed from the first function."
}

function func2 {
    echo "This message was displayed from the second function."
}

function func3 {
    echo "This message was displayed from the third function."
}

最佳答案

你必须返回到一个新的行或使用 ; 在 shell 语句之前 (if, then, elif, fi …).

您还必须在使用之前声明您的函数。

#!/bin/bash
#ask the user for a number between 1 and 3
#create some functions, write out the function number
echo "Enter a number between 1 and 3: "
read number

function func1 {
    echo "This message was displayed from the first function."
}

function func2 {
    echo "This message was displayed from the second function."
}

function func3 {
    echo "This message was displayed from the third function."
}

#which function should be called?
if [ $number -eq 1 ]; then func1
elif [ $number -eq 2 ]; then func2
elif [ $number -eq 3 ]; then func3; fi

关于linux - elif 的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25960353/

相关文章:

c# - 防止命令提示符自动关闭(CS 脚本)

perl - 使用 perl 应用补丁文件?

c - 两次向 Linux 内核双链表添加元素

PHP 日志文件颜色

linux - Logger 命令在 CentOS 中不起作用?

string - 在 if 语句中带有变量的 bash 通配符

linux - Bash:使用字符串变量一个接一个地运行命令

bash - bash 脚本如何在不使用 uudecode 的情况下写出二进制文件?

c++ - 在 C++ 中,我可以使用多线程工具将 UNIX 信号与我的主程序同步吗?

linux - read_lock和write_lock的优点