验证bash从read中传递的参数数量 [英] Validate the number of arguments passed in bash from read

查看:63
本文介绍了验证bash从read中传递的参数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于验证用户输入的问题,该输入与用户在bash脚本中传递的参数数量有关.例如,如果我使用:

I have a question about validating user input regarding number of arguments passed by the user in a bash script. For example, if I use:

if [[ $# -eq 2 ]]
then...

将检查是否从命令行传递了2个参数,如下所示:

that will check if 2 arguments passed from the command line like this:

./somescript.sh arg1 arg2

但是当询问用户时如何验证用户是否传递了两个参数?例如:

but how to validate if user passed 2 arguments when asked? For example:

echo "Type 2 names:"
read...
if [[ user passed more || less than 2 arguments]]
   echo "incorrect number of names"

现在,如果我尝试使用 $#-eq 2 ,它将无法正常工作.

Now if I try to use $# -eq 2 it doesn't work.

做这件事的正确方法是什么?

What's the proper way to do it?

推荐答案

使用数组:

read -r -a array
if [[ "${#array[@]}" -eq 2 ]]; then ...

查看以下内容的输出:

declare -p array

这篇关于验证bash从read中传递的参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆