系统相关
首页 > 系统相关> > 在linux shell脚本中if … elif statemets出错

在linux shell脚本中if … elif statemets出错

作者:互联网

#!/bin/bash
echo "enter your choice :"
echo "1 Addition"
echo "2 subtract"
echo "3 Multiplication"
read er
echo "enter the first number : "
read a
echo "enter the second number : "
read b
if [ $er="1" ]
then
sum=`expr $a + $b`
echo "sum of two numbers is $sum"
elif [ $er="2" ]
then
sub=`expr $a - $b`
echo "the diff of two numbers is $sub"
exit 0
elif [ $er="3" ]
then
mult=`expr $a * $b`
echo "the div of two numbers is $mult"
exit 0
else
echo "invalid choice"
fi

这是一个简单的计算器脚本.但它只会在第一个if语句之后执行,之后它不会执行elif语句,即使条件为乘法和减法都为真.

解决方法:

在测试中,你需要在=周围的空间,否则$er = 1(例如)将不会被正确地解释为比较.

if [ "$er" = "1" ]           # or:  if [ "$er" -eq 1 ]
then
sum=`expr "$a" + "$b"`       # or:  sum=$( expr "$a" + "$b" )  or: sum=$(( a + b ))
echo "sum of two numbers is $sum"
elif [ etc...

还要注意变量扩展的引用.稍后在代码中你还需要在mult =`expr $a * $b`中引用*,这样它就不会被解释为文件名通配模式.

您可以使用等效的$((…))(算术扩展)替换每个expr.在过去的几十年里,expr已经不再使用了.

也不鼓励命令替换的反引号. $(…)语法在很多方面都更好.例如,它更好地嵌套:

result=$( echo $( echo a ) $( echo b ) )  # pretty much impossible with backticks

…并且报价也更好,因为$(…)内外的报价不会相互干扰.

也可以看看:

> Have backticks (i.e. `cmd`) in *sh shells been deprecated?
> Security implications of forgetting to quote a variable in bash/POSIX shells

您将从此代码中使用case … esac中受益:

case "$er" in
    1) result=$(( a + b )); op='sum'        ;;
    2) result=$(( a - b )); op='difference' ;;
    3) result=$(( a * b )); op='product'    ;;
    *) printf 'Invalid choice: "%s"?\n' "$er" >&2
       exit 1
esac

printf 'The %s of %s and %s is %s\n' "$op" "$a" "$b" "$result"

标签:linux,shell-script
来源: https://codeday.me/bug/20190816/1666405.html