【发布时间】:2014-04-19 21:36:07
【问题描述】:
我稍后会使用 getopt 对命令行选项进行实际解析,但如果它们的选项存在,我想尽早启用一些标志。我正在尝试在脚本开头使用正则表达式解析它们:
这是我目前所拥有的,但它不起作用。我似乎找不到任何其他人这样做的例子(可能是一个原因,不确定是什么):
# Enable extended pattern matching features.
shopt -s extglob
# Internal values & flag initialization.
declare -A __
__[OPT]="$@" # the command line options
__[PWD]=$(pwd) # the current directory
__[SRC]="$BASH_SOURCE" # unresolved path to executable
__[SRC_DIR]=$(dirname ${__[SRC]}) # parent directory of unresolved executable
__[BIN]=$(readlink -f "$0") # resolved path to executable
__[BIN_DIR]=$(dirname ${__[BIN]}) # parent directory of resolved executable
# Preparse option string to enable flags early.
[[ ${__[OPT]} =~ (-d\b)|(--debug\b) ]] && __[DEBUG]=true || __[DEBUG]=false
[[ ${__[OPT]} =~ (-v\b)|(--verbose\b) ]] && __[VERBOSE]=true || __[VERBOSE]=false
for key in "${!__[@]}"; do
echo "$key: ${__[$key]}"
done
编辑: 基于@mklement0 建议的解决方案
以下按预期工作:
[[ ${__[OPT]} =~ $(echo '(-d\b)|(--debug\b)') ]] && __[DEBUG]=true || __[DEBUG]=false
[[ ${__[OPT]} =~ $(echo '(-v\b)|(--verbose\b)') ]] && __[VERBOSE]=true || __[VERBOSE]=false
【问题讨论】: