简体   繁体   English

用正则表达式解析bash选项字符串

[英]Parsing bash option string with regex

I use getopt to do the actual parsing of command line options later on, but I want to enable some flags early if their options are present. 稍后,我将使用getopt进行命令行选项的实际分析,但如果要使用某些标志,我想尽早启用这些标志。 I'm trying to parse them with a regex at the beginning of my script: 我试图在脚本的开头用正则表达式解析它们:

This is what I've got at the moment, but it's not working. 这是我目前所拥有的,但是没有用。 I can't seem to find any examples of anyone else doing this (probably a reason, not sure what it is): 我似乎找不到任何其他人这样做的示例(可能是一个原因,不确定它是什么):

# 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

Edit: Solution based on advice by @mklement0 编辑:基于@ mklement0的建议的解决方案

The following works as expected: 预期的工作如下:

[[ ${__[OPT]} =~ $(echo '(-d\b)|(--debug\b)') ]] && __[DEBUG]=true || __[DEBUG]=false
[[ ${__[OPT]} =~ $(echo '(-v\b)|(--verbose\b)') ]] &&  __[VERBOSE]=true || __[VERBOSE]=false

\\b is not recognized as a word-boundary marker by the =~ operator. =~运算符不能将\\b识别为单词边界标记。 Just use a space instead (since spaces will separate options in ${__[OPT]} anyway). 只需使用空格即可(因为无论如何空格都会分隔${__[OPT]} )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM