Bash如果阻止elif

时间:2017-02-11 06:27:53

标签: bash if-statement scripting

我正在尝试编写计算器脚本,但第一个if会阻止elif。我的意思是,当我尝试运行它时,按1,但它就像我按下2一样运行。这是我的代码。

echo "For Advanced mode press 1"
echo "For Help press 2"

loop=1
while [ $loop=1 ]; do

    read n

    if [ $n=2 ]; then
            echo "To use the calculator follow the promptings."
            echo "If asked, the operators are: "
            echo "* for multiplication, / for division."
            echo "+ for addition, - for subtraction."
            echo "% for modulus, which is division remainder"
            echo "== is equal to, != is not equal to."
            echo "** for exponents" 
            n=""

    elif [ $n=1 ]; then
            read a
            break
    fi

done
echo "_______________________"
echo "What would you like to do?"
echo "Press 1 for basic arith"
echo -n "Press 2 for geometry"
read choice
loop=2

if [ $choice=1]; then
    while [ $loop=2 ]; do
        echo -n "Enter X Value: "
        read x
    echo -n "Enter Operator: "
    read op
    echo -n "Enter Y Value: "
    read y
    ans=$((x $op y))
    echo "$x $op $y = $ans"
    echo "____________________"
    echo "To input a new function, press enter"
    read cont
    done
fi

2 个答案:

答案 0 :(得分:3)

[内置用于评估条件。在开始[之后必须有一个空格,在结束]之前必须有一个空格,否则它的语法不正确。

[ ... ]表达式中,您可以使用各种条件运算符。一个这样的运算符是=。您必须在操作员之前和之后放置空格,否则它不会被识别为操作员。

例如,[ $n=2 ]的值为n的{​​{1}}将被评估为[ 1=2 ]1=2未被评估为条件,因为它周围没有空格。 1=2将被评估为字符串" 1 = 2"。 Bash中的任何非空字符串都是 truthy ,因此语句[ 1=2 ]产生true,即使它不是"看起来像"这是真的。

您必须编写[ "$n" = 2 ]以便=被解释为条件运算符,并且表达式不会成为单个字符串。请注意,空格在Bash中非常重要。空格分隔程序的逻辑元素,没有空格表达式连接为字符串。

另请注意,我在变量周围添加了双引号。这是为了在变量为空的情况下保护表达式。例如,如果您编写[ $n = 2 ]且变量为空,则表达式将被评估为[ = 2 ],这是一个格式错误的表达式,并且脚本将崩溃并出现错误。

答案 1 :(得分:0)

在条件元素之间加上空格,例如$n = 2而不是$n=2。你应该将它的参数作为空格分隔的单词传递。所以你的代码应如下:

echo "For Advanced mode press 1"
echo "For Help press 2"

loop=1
while [ $loop = 1 ]; do

    read n

    if [ $n = 2 ]; then
        echo "To use the calculator follow the promptings."
        echo "If asked, the operators are: "
        echo "* for multiplication, / for division."
        echo "+ for addition, - for subtraction."
        echo "% for modulus, which is division remainder"
        echo "== is equal to, != is not equal to."
        echo "** for exponents" 
        n=""

    elif [ $n = 1 ]; then
        read a
        break
    fi

done
echo "_______________________"
echo "What would you like to do?"
echo "Press 1 for basic arith"
echo -n "Press 2 for geometry"
read choice
loop=2

if [ $choice = 1 ]; then
    while [ $loop = 2 ]; do
        echo -n "Enter X Value: "
        read x
    echo -n "Enter Operator: "
    read op
    echo -n "Enter Y Value: "
    read y
    ans=$((x $op y))
    echo "$x $op $y = $ans"
    echo "____________________"
    echo "To input a new function, press enter"
    read cont
    done
fi