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 语句工作,但我使用了错误的吗?
解决方案
[ -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
推荐阅读
- azure-policy - 是否可以在 Azure 策略中获取调用者信息
- android - 净::ERR_CLEARTEXT_NOT_PERMITTED 离子 4
- laravel - Laravel Nova 如何覆盖 nova LoginController
- javascript - react-router v4 mocha 测试与酶浅不工作
- c# - 什么是 NetworkInterfaceType 53?
- angular8 - ngOnDestroy 时无法读取未定义的属性“data-ck-expando”
- django - 如何从 FK 关系中提取除 str 值之外的其他内容?
- sql-server - 为什么 SQL Server 没有捕捉到这一点?子查询中的拼写错误导致意外删除
- c# - 根据 ListBox 中的 SelectedItem 改变 Dictionary 的值
- c# - 使用托管标识调用 WebAPI 的逻辑应用向请求中添加了哪种令牌