验证参数数量

时间:2019-05-18 21:43:24

标签: bash

我为初学者的问题提前表示歉意,但是我无法使这段代码正常工作。我被要求制作一个基本程序,该程序要求用户输入3个数字,然后检查哪个是最高值并打印结果,并确保输入了三个数字。它可以确定哪个是他的最高数字并且即时获得它可以正确输出结果,但是我似乎无法弄清楚如何获取它来验证是否输入了三个数字。

我已经进行了研究,甚至从老师的示例中提取了一些有关如何检查参数数量的代码,但是我仍然无法使它起作用。

#!/bin/bash

echo "Please enter three numbers:"
read a b c
if [ $# -ne 3 ]
    then
    echo "You need three numbers"
    exit -1
fi
if [ $a -gt $b -a $a -gt $c ]
      then
              LARGEST=$a
elif [ $b -gt $a -a $b -gt $c ]
      then
              LARGEST=$b
elif [ $c -gt $a -a $c -gt $b ]
      then
              LARGEST=$c
elif [ $a -eq $b -a $a -eq $c -a $b -eq $c -eq $b ]
then
LARGEST="All three values are equal."
fi
echo "The largest values is $LARGEST"

当我输入三个数字(7 8 9)时,我希望返回: “最大值是9”

但是我却得到了它:

./values.sh: line 6 [0: command not found
The largest value is 9

我在这里错过明显地明显的东西吗?我知道我需要一个运算符来使我的原始if语句生效,但是我使用的是错误的语句吗?

1 个答案:

答案 0 :(得分:3)

[ -z "$c" ]测试可以解决您发布的代码。 工作代码:

#!/bin/bash

echo "Please enter three numbers:"
read a b c d
if [ -z "$c" ]
    then
    echo "You need three numbers"
    exit -1
fi
if [ -n "$d" ]
then
   echo "enter only three numbers"
   exit -1
fi
if [ $a -gt $b -a $a -gt $c ]
      then
              LARGEST=$a
elif [ $b -gt $a -a $b -gt $c ]
      then
              LARGEST=$b
elif [ $c -gt $a -a $c -gt $b ]
      then
              LARGEST=$c
elif [ $a -eq $b -a $a -eq $c -a $b -eq $c -eq $b ]
then
LARGEST="All three values are equal."
fi
echo "The largest values is $LARGEST"

输出:

$ ./t.sh
Please enter three numbers:
7 8
You need three numbers
$ ./t.sh
Please enter three numbers:
7 8 9
The largest values is 9