Linux 根据输入计算总和或乘积
我要求用户输入2个数字,s表示总和,p表示乘积。 当我运行脚本时,我看不到任何结果 这是我的剧本Linux 根据输入计算总和或乘积,linux,bash,Linux,Bash,我要求用户输入2个数字,s表示总和,p表示乘积。 当我运行脚本时,我看不到任何结果 这是我的剧本 #!/bin/bash read -p "please enter two integers, s or p to calculate sum or product of this numbers: " num1 num2 result if [ result == "s" ] then echo "num1+num2" | bc elif [ result == "p" ] then ec
#!/bin/bash
read -p "please enter two integers, s or p to calculate sum or product of this numbers: " num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc
elif [ result == "p" ]
then
echo $((num1*num2))
fi
您正在比较字符串结果,而不是变量结果的值 在$…,您可以省略前导的$,因为假定字符串是要取消引用的变量名
如果要将输入限制为整数,则没有理由使用bc。您是在比较字符串结果,而不是变量结果的值 在$…,您可以省略前导的$,因为假定字符串是要取消引用的变量名 如果您打算将输入限制为整数,则没有理由使用bc。补充,这很好地解释了问题中代码的问题,并提供了一个受[1]启发的解决方案 : [1] 除了read的-p选项外,该解决方案是兼容POSIX的;不过,它也适用于dash,dash主要是一个POSIX功能单一的shell。作为补充,它很好地解释了问题中代码的问题,并提供了一个受[1]启发的解决方案 : [1] 除了read的-p选项外,该解决方案是兼容POSIX的;不过,它也可以在dash中使用,dash主要是一个只有POSIX特性的shell
if [ "$result" = s ]; then
echo "$(($num1 + $num2))"
elif [ "$result" = p ]; then
echo "$(($num1 * $num2))"
fi
# Prompt the user.
prompt='please enter two integers, s or p to calculate sum or product of this numbers: '
read -p "$prompt" num1 num2 opChar
# Map the operator char. onto an operator symbol.
# In Bash v4+, consider using an associative array for this mapping.
case $opChar in
'p')
opSymbol='*'
;;
's')
opSymbol='+'
;;
*)
echo "Unknown operator char: $opChar" >&2; exit 1
;;
esac
# Perform the calculation.
# Note how the variable containing the *operator* symbol
# *must* be $-prefixed - unlike the *operand* variables.
echo $(( num1 $opSymbol num2 ))