首页 > 解决方案 > 验证参数的数量

问题描述

我提前为初学者的问题道歉,但我无法让这段代码正常工作。我被要求制作一个基本程序,询问用户 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 语句工作,但我使用了错误的吗?

标签: bash

解决方案


[ -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

推荐阅读