如何在shell脚本中使用命令行参数找到最大的三个数字?

时间:2017-05-10 05:53:12

标签: unix

请帮我执行这个。我是新学习unix! 编写一个shell脚本来查找三个数字中的最大数字。假设输入是作为命令行参数给出的,如果没有给出这三个数字,则显示错误消息“缺少命令行参数”。

示例输入1:

10 20 30

示例输出1:

30是最大数字

示例输入1:

10 10 10

示例输出1:

所有三个数字相等

示例输入1:

10 10 1

示例输出1:

我无法弄清楚哪个数字最大

4 个答案:

答案 0 :(得分:1)

read a b c
if [[ $a == 0 || $b == 0 || $c == 0 ]]; then
    echo "command line arguments are missing"
elif [[ $a == $b && $b == $c ]]; then
    echo "All the three numbers are equal"
elif [[  $a == $b && $b > $c  ||  $b == $c && $c > $a ||  $a == $c && $a > $b  ]]; then
    echo "I cannot figure out which number is biggest"
else
    if [[ $a > $b && $a > $c ]]; then 
        echo "$a is Biggest number"
    elif [[ $b > $a && $b > $c ]]; then
        echo "$b is Biggest number"
    else
        echo "$c is Biggest number"
    fi
fi

答案 1 :(得分:0)

在awk中。适用于3个值,但很容易概括:

$ echo 20 20 20 | awk -v RS="[ \n]" '
{ a[$0] }                  # hash all values to a
END {
    for(i in a) {          # loop all values in hash
        if(m==""||i>m)     # decide bigger
            m=i
        j++ }              # count values in hash
    switch(j) {
    case "1": 
        print "All equal"  # not sure if these make any sense:
        break
    case "2": 
        print "No figure"  # if repeating values, there is still biggest value
        break
    case "3": 
        print m " biggest"
        break
    }
}'
All equal

答案 2 :(得分:0)

if [ $# -ne 3 ] then echo "command line arguments are missing" exit 1 fi if [ $1 -eq $2 -a $1 -eq $3 ] then echo "All the three numbers are equal" elif [[ $1 -eq $2 && $1 -ge $3 || $2 -eq $3 && $2 -ge $1 || $3 -eq $1 && $1 -ge $2 ]] then echo "I cannot figure out which number is biggest" elif [ $1 -gt $2 -a $1 -gt $3 ] then echo "$1 is Biggest number" elif [ $2 -gt $3 -a $2 -gt $1 ] then echo "$2 is Biggest number" else echo "$3 is Biggest number" fi

答案 3 :(得分:-1)

在这里看一下:

if [ $# -lt 2 ]
then 
    echo "command line arguments are missing"
elif [ $1 -eq $2 ]&&[ $2 -eq $3 ]
then
    echo "All the three are equal"
elif [ $1 -eq $2 ]||[ $1 -eq $3 ]
then
    echo "I cannot figure out which number is biggest"
elif [ $1 -gt $2 ]
then
    if [ $1 -gt $3 ]
    then
        echo "$1 is biggest number"
    else
        echo "$3 is biggest number"
    fi
elif [ $2 -gt $3 ]
then
    echo "$2 is biggest number"
else
    echo "$3 is biggest number"
fi
相关问题