Syntax error =~ operator in msysgit bash

后端 未结 4 1904
迷失自我
迷失自我 2020-12-18 19:40

I\'m trying to add a function to my bash_profile for msysgit:

function git-unpushed {
    brinfo=$(git branch -v | grep git-branch-name)
    if          


        
4条回答
  •  孤城傲影
    2020-12-18 20:06

    Here is a solution that supports extracting matched strings. If the operator =~ is not supported by bash, then the sed command is used (installed with msysgit)

    if eval "[[ a =~ a ]]" 2>/dev/null; then
        regexMatch() { # (string, regex)
            eval "[[ \$1 =~ \$2 ]]"
            return $?
        }
    elif command -v /bin/sed >/dev/null 2>&1; then
        regexMatch() { # (string, regex)
            local string=$1
            if [[ ${2: -1} = $ ]]; then
                local regex="(${2%$})()()()()()()()()$"
            else
                local regex="($2)()()()()()()()().*"
            fi
            regex=${regex//\//\\/}
            local replacement="\1\n\2\n\3\n\4\n\5\n\6\n\7\n\8\n\9\n"
            local OLD_IFS=$IFS
            IFS=$'\n'
            BASH_REMATCH=($(echo "$string" | /bin/sed -rn "s/$regex/$replacement/p" | while read -r; do echo "${REPLY}"; done))
            IFS=$OLD_IFS
            [[ $BASH_REMATCH ]] && return 0 || return 1
        }
    else
        error "your Bash shell does not support regular expressions"
    fi
    

    Usage example:

    if regexMatch "username@host.domain" "(.+)@(.+)"; then
        echo ${BASH_REMATCH[0]}
        echo ${BASH_REMATCH[1]}
        echo ${BASH_REMATCH[2]}
    fi
    

提交回复
热议问题