elif的语法错误

时间:2014-09-21 14:42:06

标签: 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."
}

2 个答案:

答案 0 :(得分:2)

您必须在shell语句(;ifthenelif ...)之前返回新行或使用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

答案 1 :(得分:2)

对于这样的多个if/elif,有时更容易使用case语句,例如:

func1() { echo "func1"; }
func2() { echo "func2"; }
func3() { echo "func3"; }

while read -r -p 'Enter a number between 1 and 3:>' number
do
    case "$number" in
        1) func1 ; break ;;
        2) func2 ; break ;;
        3) func3 ; break ;;
        q) exit;;
        *) echo "Wrong input" >&2;; #error message
    esac
done
echo "end of loop"

评论:请勿使用function关键字。它是 bashism ,定义shell函数的可移植方式是

funcname() {
}

它也有点短......:)