如何让Bash脚本处理多个命令行选项并执行所有对应逻辑?
修复Bash脚本中getopts无法处理多选项的问题
你的脚本问题出在getopts的选项定义上:你给每个选项字母后面都加了冒号(比如:d:h:s:),这会让getopts认为这些选项必须携带参数。当你执行./script.sh -d -a时,-a会被当成-d的参数,而不是独立选项,所以只会处理第一个选项。
修改方法
- 去掉选项字符串中每个字母后的冒号,因为你的选项不需要参数;
- 用变量收集所有选项对应的输出,最后统一打印成空格分隔的格式。
修改后的完整脚本
if [ $# -eq 0 ] then du else output="" while getopts :dhsrfa option; do case $option in d) output="$output d";; h) output="$output h";; s) output="$output s";; r) output="$output r";; f) output="$output f";; a) output="$output a";; \?) echo 'option invalide,-h pour obtenir l aide' >&2; exit 1;; esac done # 移除开头多余的空格后输出 echo "${output# }" fi
测试效果
执行./script.sh -d -a会输出:d a;
执行./script.sh -a -s -r会输出:a s r,完全符合需求。
内容的提问来源于stack exchange,提问作者TristanMas
相关产品推荐
相关产品推荐

