bash - 将脚本选项/参数分配给变量并手动循环
问题描述
我正在使用BashFAQ 手动循环的变体,我想将其转换为函数并将参数分配给局部变量,但我无法找出正确的语法。这是我所拥有的:
function parseArguments() {
local arguments=( "$@" )
while :; do
case ${1:-} in
-d|--debug)
set -o xtrace
# [...more stuff...]
;;
-p|--prompt)
IsPromptEnabled=true
;;
--)
shift
break
;;
-?*)
error ${LINENO} "\"${1:-}\" is an unknown option" 1
;;
*)
break
esac
shift
done
}
parseArguments "$@"
这可以正常工作,直到我尝试用 from 的值替换$1
循环中的值arguments
。${arguments[0]}
以及我能想到的所有其他变体都失败了,我想了解原因(并找出解决方案)。
解决方案
You should loop over the array
function parseArguments() {
local arguments=( "$@" )
for a in "${arguments[@]}"
do
case ${a:-} in
-d|--debug)
set -o xtrace
# [...more stuff...]
;;
-p|--prompt)
IsPromptEnabled=true
;;
--)
# shift
break
;;
-?*)
error ${LINENO} "\"${a:-}\" is an unknown option" 1
;;
*)
break
esac
shift
done
}
parseArguments "$@"
推荐阅读
- javascript - 在 React js 中选择特定下拉值时禁用按钮
- java - Hibernate 抛出 java.sql.SQLException:@Enumerated(EnumType.STRING) 的整数值异常不正确
- multithreading - Delphi 在 TWebModule 中使用 TTask (ISAPI - IIS)
- python - 如何根据在特定页面上按下的下一步按钮调用不同的功能
- ada - 是否有对应于 ASIS 的 Flat_Element_Kind 的 Libadalang 枚举或类型?
- sql - 将 Postgres IPv6 列 TEXT 字段转换为 JSON
- ios - 滑块上的拇指不动
- angular - Angular 下拉菜单中的服务器端分页和过滤
- go - 如何将嵌套模块路径中的某些内容带入当前范围?
- python - 有没有办法在 django 文件中使用函数的返回值作为默认值?