我看到的所有东西getopt或者getopts只是支持单字符选项的略微发烧友(例如-h但不是--help).我想做一些花哨的长期选择.
zie*_*mer 17
我已经做了一些类似这样:
_setArgs(){
while [ "${1:-}" != "" ]; do
case "$1" in
"-c" | "--configFile")
shift
configFile=$1
;;
"-f" | "--forceUpdate")
forceUpdate=true
;;
"-r" | "--forceRetry")
forceRetry=true
;;
esac
shift
done
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这可以很好地支持单字符和更长的选项.它允许将值与每个参数相关联,如同的情况一样--configFile.它也是相当可扩展的,没有任何人为限制,可以配置哪些选项等.
如上所述,"${1:-}"在bash"strict"模式(set -euo pipefail)中运行时,可防止出现"未绑定变量"错误.
假设您"想要做一些花哨的长选项",无论使用哪种工具,只需使用getopt(getopts似乎主要用于便携性至关重要).这是一个关于您将获得的最大复杂性的示例:
params="$(getopt -o e:hv -l exclude:,help,verbose --name "$(basename "$0")" -- "$@")"
if [ $? -ne 0 ]
then
usage
fi
eval set -- "$params"
unset params
while true
do
case $1 in
-e|--exclude)
excludes+=("$2")
shift 2
;;
-h|--help)
usage
;;
-v|--verbose)
verbose='--verbose'
shift
;;
--)
shift
break
;;
*)
usage
;;
esac
done
Run Code Online (Sandbox Code Playgroud)
使用此代码,您可以指定-e/ --exclude多次,${excludes[@]}并将包含所有给定的排除.处理后(--始终存在)存储的任何内容$@.
| 归档时间: |
|
| 查看次数: |
9728 次 |
| 最近记录: |