gpt4 book ai didi

linux - shell 测试条件错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:21 24 4
gpt4 key购买 nike

无法让它运行。我确定我做错了什么,我确定我忽略了一些东西。

a=3

echo "Type in the first Grade Number."
read num1;
echo "Type in the Second Grade Number."
read num2;
echo "Type in the third Grade Number."
read num3;

echo \($num1 + $num2 + $num3\)/$a | bc
read num;

if [ $num-lt 79 ]
then
echo "The Grade Number is an C."

elif [ $num-lt 89 ]
then
echo "The grade number is an B."

elif [ $num-lt 99 ]
then
echo "Your grade number is an A."

elif [ $num-lt 60 ]
then
echo "You have a failing number"
fi

最佳答案

if [ $num-lt 79 ]

需要$num-lt 之间有一个空格。没有它,它就是两个参数的表达形式。根据 bash 手册页,双参数形式的计算如下:

If the first argument is !, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators listed above under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true. If the first argument is not a valid unary conditional operator, the expression is false.


您可能还想查看您的脚本的其他一些问题。

首先,您不需要在read 语句末尾使用; 字符。它们不会造成破坏,但它们是多余的。

其次,您似乎输出了三个成绩的平均值,然后要求另一个数字,该数字已检查成绩。我原以为平均值本身会是更好的衡量标准:

num=$(echo "($num1 + $num2 + $num3) / $a" | bc)

第三,您的逻辑意味着永远不会输出不及格成绩。对于小于 60 的数字,小于 79 的数字已经被初始测试捕获。更好的方法是按顺序检查边界,例如:

if [ $num -lt 60 ] ; then
echo "You failed!"
elif [ $num -lt 80 ] ; then
echo "You got a C, just made it."
elif [ $num -lt 90 ] ; then
echo "You got a B, not bad."
elif [ $num -lt 100 ] ; then
echo "You got an A, excellent."
else
echo "You got an A, perfect score."
fi

关于linux - shell 测试条件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com