如何在shell中获取当前的git分支

jdp*_*jdp 2 bash shell

我正在尝试编写一个shell脚本,如果当前的git分支与预定义的值不匹配,该脚本应该失败.

if $gitBranch != 'my-branch'; then
   echo 'fail'
   exit 1
fi
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的shell脚本编写技巧还不尽如人意:如何在我的变量中获取当前的git分支?

Wil*_*ell 9

要获取当前分支的名称: git rev-parse --abbrev-ref HEAD

所以,要检查:

if test "$(git rev-parse --abbrev-ref HEAD)" != my-branch; then
  echo Current branch is not my-branch >&2
  exit 1
fi
Run Code Online (Sandbox Code Playgroud)