bash - 在 bash 中解析命令行参数和标志的组合
问题描述
我正在尝试编写 bash 脚本,它将读取多个文件名和一个目标目录,这是可选的。
./myfile -t /home/users/ file1 file2
我已经尝试了以下代码,但我无法处理下面提到的不同场景:
while getopts "t:" opt; do
case $opt in
t)
echo "-t was triggered, Parameter: $OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG"
exit 1
;;
:)
echo "Option -$OPTARG requires an argument."
exit 1
;;
esac
done
但是代码应该处理不同的场景,比如:
、、
./myfile file1 file2 -t /home/users/
和
应该能够读取文件。./myfile file1 -t /home/users/ file2 file3
./myfile file1 file2 file3 file4
解决方案
在您的while
循环之后,您需要shift
输出任何选项及其参数。即使没有任何标志/标志争论,这也有效。
shift $(($OPTIND - 1))
然后其余的论点可用"$@"
并且可以以任何通常的方式处理。例如:
for arg in "$@"
do
something_with "$arg"
done
有关更多信息,请在此处查看我的回答。
推荐阅读
- javascript - 是否可以在组件之外使用 route.meta 属性?
- mysql - 使用 MySQL 测试数据库的 Github 操作
- algorithm - 此 Word Break DFS + 记忆解决方案的时间复杂度
- python - 如何在python中用正斜杠替换方括号中的数字
- react-native - react-native init MyProject --version 0.58.6 但每次我这样做时,都会出现如下错误
- python - (discord.py) 冒充另一个用户
- ruby-on-rails - ROR - 如何将 rubygem 更新到特定版本?
- c# - 短跑、跳跃和主菜单不起作用
- javascript - 未捕获的 ReferenceError:未定义控制器
- python-3.x - PermissionError:[Errno 13] 权限被拒绝:无法保存 csv 文件