我需要在大学做一个练习,它是关于读取 3 个值并确定是否存在重复值,哪个值最大,哪个值最小,想法是如果您输入任何重复值,shell 应该打印一条消息并停止计算,但我无法完成这部分。
这是代码:
#!/bin/sh
echo " A value "
read A
echo " B value "
read B
echo " C value "
read C
# Print the input
echo " INPUT "
echo " A = $A "
echo " B = $B "
echo " C = $C "
# search duplicated values
if [[ $A -eq $B ]] || [[ $A -eq $C ]];then
echo " Duplicated values please check "
elif [[ $B -eq $A ]] || [[ $B -eq $C ]];then
echo " Duplicated values please check "
elif [[ $C -eq $A ]] || [[ $C -eq $B ]];then
echo " Duplicated values please check "
fi
# greatest value
if [[ $A -gt $B ]] || [[ $A -gt $C ]];then
echo " A $A +"
elif [[ $B -gt $A ]] || [[ $B -gt $C ]];then
echo " B $B +"
elif [[ $C -gt $A ]] || [[ $C -gt $B ]];then
echo " C $C +"
fi
# less value
if [[ $A -lt $B ]] || [[ $A -lt $C ]];then
echo " A $A -"
elif [[ $B -lt $A ]] || [[ $B -lt $C ]];then
echo " B $B -"
elif [[ $C -lt $A ]] || [[ $C -lt $B ]];then
echo " C $C -"
fi
现在,如果我输入重复的代码,例如 A=3 B=5 C=3
代码进行计算并打印存在重复值,我只需要一条消息告诉我我引入了重复值。
我怎样才能完成这件事?
感谢您的帮助。
答案1
您可以exit
在适当的地方,例如:
# search duplicated values
if [[ $A -eq $B ]] || [[ $A -eq $C ]];then
echo " Duplicated values please check "
exit
elif [[ $B -eq $A ]] || [[ $B -eq $C ]];then
echo " Duplicated values please check "
exit
elif [[ $C -eq $A ]] || [[ $C -eq $B ]];then
echo " Duplicated values please check "
exit
fi
您还可以使用数字退出状态退出,例如:exit 2
。也可以看看http://tldp.org/LDP/abs/html/exitcodes.html和http://tldp.org/LDP/abs/html/exit-status.html
答案2
你可以这样做。
#!/bin/sh
echo "A value"
read A
echo "B value"
read B
#Print the input
echo " A = $A "
echo " B = $B "
#serch duplicated values
if [ $A -eq $B ] ;then
echo "Duplicated values please check "
exit
fi
echo "C value"
read C
echo " C = $C "
if [ $C -eq $A ] || [ $C -eq $B ];then
echo " Duplicated values please check "
exit
fi
# greatest value
if [ $A -gt $B ] && [ $A -gt $C ];then
echo " A $A + "
elif [ $B -gt $A ] && [ $B -gt $C ];then
echo " B $B +"
elif [ $C -gt $A ] && [ $C -gt $B ];then
echo " C $C +"
fi
# less value
if [ $A -lt $B ] && [ $A -lt $C ];then
echo " A $A -"
elif [ $B -lt $A ] && [ $B -lt $C ];then
echo " B $B -"
elif [ $C -lt $A ] && [ $C -lt $B ];then
echo " C $C -"
fi
当你输入相同的A和B时,你不需要输入C。并且比较它们,你可能需要“&&”,而不是“||”。