bash 如何使用shell脚本从5个数字中获取最大数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23055644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get greatest number out of 5 number using shell script
提问by Vishal
I am trying to find the greatest number from 5 given numbers in shell script. I am testing my code on Ideone.com in Bash category. I am getting error
我试图从 shell 脚本中的 5 个给定数字中找到最大的数字。我正在 Ideone.com 上的 Bash 类别中测试我的代码。我收到错误
Runtime error time: 0.02 memory: 5312 signal:-1
运行时错误时间:0.02 内存:5312 信号:-1
Here is the code
这是代码
read -p "Enter first Number:" n1
read -p "Enter second Number:" n2
read -p "Enter third Number:" n3
read -p "Enter fourth Number:" n4
read -p "Enter fourth Number:" n5
if[ [ n1 -gt n2 ] && [ n1 -gt n2 ] && [ n1 -gt n3 ] && [ n1 -gt n4 ] && [ n1 -gt n5 ]] ; then
echo "$n1 is a Greatest Number"
elif[ [ n2 -gt n3 ] && [ n2 -gt n3 ] && [ n2 -gt n4 ] && [ n2 -gt n5 ]] ; then
echo "$n2 is a Greatest Number"
elif[ [ n3 -gt n4 ] && [ n3 -gt n5 ] ] ; then
echo "$n3 is a Greatest Number"
elif[ n4 -gt n5 ] ; then
echo "$n4 is a Greatest Number"
else
echo "$n5 is a Greatest Number"
fi
What is the problem? kindly guide
问题是什么?亲切指导
回答by user3132194
It seems your problem is spaces. Add spaces after "if" "elif" and before "]"
看来你的问题是空格。在“if”“elif”之后和“]”之前添加空格
And how about
怎么样
echo -e "$n1 \n $n2 \n $n3 \n $n4 \n $n5" | sort -n -r | head -n 1
回答by twalberg
You could do it much more efficiently, without invoking external commands like sort
and head
/ tail
:
您可以更有效地完成此操作,而无需调用sort
和head
/等外部命令tail
:
max2()
{ if (( "" > "" ))
then
echo ""
else
echo ""
fi
}
max5()
{ tmp1=$(max2 "" "")
tmp2=$(max2 "" "")
tmp3=$(max2 "$tmp1" "$tmp2")
echo $(max2 "$tmp3" "")
}
m=$(max5 "$n1" "$n2" "$n3" "$n4" "$n5")
If you know that all the numbers are small enough, you could use return $n
instead of echo $n
, and then capture return codes instead of the textual representations of the numbers.
如果您知道所有数字都足够小,则可以使用return $n
代替echo $n
,然后捕获返回代码而不是数字的文本表示。
回答by mato
Here's a simple shell function to find max value out of numeric parameters passed:
这是一个简单的 shell 函数,用于从传递的数字参数中查找最大值:
max()
{
local m=""
for n in "$@"
do
[ "$n" -gt "$m" ] && m="$n"
done
echo "$m"
}
Example: max 1 3 2
returns 3
示例:max 1 3 2
返回3