📅  最后修改于: 2023-12-03 15:00:57.975000             🧑  作者: Mango
在使用 Git 管理代码时,我们通常需要在本地维护不同的分支,以便于并行开发、测试、修复等操作。本文将介绍如何在 Shell/Bash 环境中使用 Git 命令获取本地分支。
使用 git branch
命令可以查看当前所在分支,加上 -a
参数可以查看所有分支(包括本地和远程)。
# 获取当前分支名称
$ git branch
* main
# 查看所有分支
$ git branch -a
* main
remotes/origin/HEAD -> origin/main
remotes/origin/main
在 Shell/Bash 脚本中,我们可以使用 git branch --show-current
命令获取当前分支名称,该命令需要 Git 版本在 2.22 及以上。
# 获取当前分支名称
current_branch=$(git branch --show-current)
echo "Current branch is $current_branch"
使用 git branch
命令加上 -l
参数可以只查看本地分支列表,加上 -r
参数可以只查看远程分支列表。
# 查看本地分支列表
$ git branch -l
* main
feature-1
feature-2
# 查看远程分支列表
$ git branch -r
origin/HEAD -> origin/main
origin/main
origin/feature-1
origin/feature-2
在 Shell/Bash 脚本中,我们可以使用如下命令获取本地分支列表:
# 获取本地分支列表
local_branches=$(git branch -l | cut -c 3-)
echo "Local branches are: $local_branches"
其中 cut -c 3-
命令用于去掉 git branch
命令输出的 *
前缀。
可以使用 git rev-parse --show-toplevel
命令获取当前工作区根目录(即 Git 仓库的根目录)。
# 获取当前工作区根目录
repo_root=$(git rev-parse --show-toplevel)
echo "Repository root is $repo_root"
可以使用 git rev-parse HEAD
命令获取当前分支最新一次提交的哈希值。
# 获取当前分支最新一次提交的哈希值
commit_hash=$(git rev-parse HEAD)
echo "Last commit hash is $commit_hash"
可以将上述命令中的 HEAD
参数替换为其他分支名称,以获取该分支最新一次提交的哈希值。
# 获取 feature-1 分支最新一次提交的哈希值
feature_1_hash=$(git rev-parse feature-1)
echo "Last commit hash of feature-1 branch is $feature_1_hash"
通过以上命令,可以方便地在 Shell/Bash 脚本中获取本地分支名称、分支列表、仓库根目录和最新一次提交的哈希值等信息,帮助程序员进行分支管理和开发操作。