使用 bash 获取当前分支并存储为变量

Dav*_*Liu -1 git bash

当我使用 Kubernetes 时,我想运行依赖于我的活动分支的命令。因此,在给定当前分支的情况下,拥有别名将帮助我使用自动运行命令的其他别名。

我试图使用函数将当前活动本地分支的名称存储到 bash 别名中,以便我可以运行其他脚本而不必担心指定活动分支,但我一直遇到错误。

function branch ()
{
    local result='git branch | grep ^\* | cut -c 3-';
    echo "$result"
}

alias get_branch=$(branch)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行它时,我得到:

    usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
               [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
               [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
               [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
               <command> [<args>

.... (Same output as just entering 'git')
Run Code Online (Sandbox Code Playgroud)

(当列出活动的 git 分支时,cut -c 3-删除其后面的 和 空格)例如*

* feature/ch20372 ch20372 ch12345

奇怪的是这两项工作:

alias IMLAZY='git branch |grep \* | cut -d " " -f2'
alias TEST='git branch | grep ^\* | cut -c 3-'
Run Code Online (Sandbox Code Playgroud)

这让我想到

  1. 我的其他地方可能有语法问题~/.bash_aliases吗?

  2. ZSH 有问题吗?

  3. 函数定义中的某处存在语法错误?

Rom*_*eri 5

使用适当的管道命令可能会更简单:git rev-parse

(此处gitcb为当前分支命名,可以任意)

alias gitcb='git rev-parse --abbrev-ref HEAD'
Run Code Online (Sandbox Code Playgroud)