bash - 如何在 bash 中访问命令行标志的多个选项
问题描述
我想访问多个命令行输入的标志,但我无法让它工作。输入顺序不受我控制,格式为(# 是数字,不是注释)
./program.sh -a -b # #
./program.sh -b # # -a
./program.sh -b # #
-a
没有选项,它只是一个开关-b
后面总是跟着两个数字。
我尝试过使用getopts
, 并且适用于-a
的第一个数字-b
,但我无法访问第二个数字。有时-a
,-b
将输入的“剩余部分”视为字符串并不能按预期工作。我尝试使用一个循环,当它找到时-b
,查看要设置的下两个值,如下所示:
for i in "$@"; do
case "$i" in
-a)
upperCase=true;
;;
-b)
first=$(($i+1));
second=$(($i+2));
;;
*)
;;
esac
done
输出应该是两个方向上从 # 到 # 的字母,但我已经开始工作了,我唯一的问题实际上是接收输入。
解决方案
也许这个循环会起作用,而不是:
while [[ $# -gt 0 ]]
do
case "$1" in
-a)
upperCase=true;
;;
-b)
first=$2; # Take the next two arguments
second=$3;
shift 2 # And shift twice to account for them
;;
*)
;;
esac
shift # Shift each argument out after processing them
done
$(($i+1))
只是向变量添加一个i
,而不是根据需要获取下一个位置参数。
推荐阅读
- botframework - MS Teams 示例未向侦听机器人应用程序发送消息
- vbscript - 如何在 netstat 命令中传递参数?
- javascript - What range of problems jest.fn() is intended to solve?
- mongodb - 将 MongoDB 迁移到 DynamoDB
- r - R混淆矩阵错误 - 分类树
- google-app-maker - 两个有关系的表 --> 插入表单 --> 显示多个属性但插入 Id
- oracle - 如何包含 DBI Oracle 连接的 SID?
- android - 使用 JSONObject 的 Android 应用程序无法在使用 API 19 的设备上运行
- c# - 在子类的子类中调用方法
- angular - Angular 6.1.0 - 恢复滚动位置未按预期工作