【问题标题】:Parsing bash option string with regex使用正则表达式解析 bash 选项字符串
【发布时间】: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

【问题讨论】:

    标签: regex bash options


    【解决方案1】:

    \b 未被=~ 运算符识别为字边界标记。只需使用空格(因为空格会分隔${__[OPT]} 中的选项)。

    [[ ${__[OPT]} =~ (-d\ )|(--debug\ ) ]] && ...
    

    【讨论】:

    • 虽然使用空格是个好建议,但它取决于平台(不幸的是)=~ 是否识别 \b。图片被 bash 4.x 中关于正则表达式 literals 的错误弄糊涂了;使用中间变量进行测试:尝试re='a\b'; [[ 'a ' =~ $re ]] && echo YES;在 Linux 上,它会成功;相比之下,它不适用于 OSX(您必须使用 re='a[[:>:]]')。
    • 我最初尝试使用空格,但是当标志位于选项字符串的末尾时(即:“bish -d”),它不匹配。
    • 感谢您提供有关 bash 4.x 错误的信息,这似乎是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2019-12-10
    • 2010-11-22
    • 2011-10-14
    相关资源
    最近更新 更多