bash - 验证从读取的 bash 中传递的参数数量

标签 bash shell

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

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

这将检查是否从命令行传递了 2 个参数,如下所示:
./somescript.sh arg1 arg2

但是如何验证用户是否在询问时传递了 2 个参数?
例如:
echo "Type 2 names:"
read...
if [[ user passed more || less than 2 arguments]]
   echo "incorrect number of names"

现在,如果我尝试使用 $# -eq 2它不起作用。

正确的做法是什么?

最佳答案

使用数组:

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

见输出:
declare -p array

关于bash - 验证从读取的 bash 中传递的参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60909805/

相关文章:

linux - 如何获取管道中第一个命令的退出状态?

bash - 如何快速检查私有(private) rsa key 是否仍然适用于 bash 中的一堆服务器?

linux - shell 脚本中的信号处理

linux - 变量在 shell 脚本中不起作用

php - 在 linux bash 中运行 php 脚本(php 函数)

linux - 在 "find"命令中使用 printf

python - 在 Windows 上使用 bash 调用 python 时使用 linux 样式路径

java - 从 Perl 运行 screen

bash - GNU Parallel - 检测并行运行的命令已完成

linux - 某些命令无法通过 ssh(shell)在远程服务器上运行