如何同时查看多个Git仓库的当前分支
一次性查看多仓库Git分支的方法
方法1:单行Shell命令(适合临时使用)
假设你的三个仓库目录分别是repo-a、repo-b、repo-c,且都位于当前目录下,直接执行以下命令:
for dir in repo-a repo-b repo-c; do echo "$dir: $(git -C "$dir" rev-parse --abbrev-ref HEAD)"; done
git -C <目录>:指定Git命令的工作目录,无需切换当前shell的路径(Git 1.8.5及以上版本支持)rev-parse --abbrev-ref HEAD:输出当前所在的分支名称
如果你的Git版本低于1.8.5,可以用子shell避免切换当前目录:
for dir in repo-a repo-b repo-c; do (cd "$dir" && echo "$dir: $(git rev-parse --abbrev-ref HEAD)"); done
方法2:编写Shell脚本(适合长期复用)
如果需要频繁执行,建议写一个脚本:
- 创建脚本文件
check_branches.sh,内容如下:
#!/bin/bash # 替换为你的三个仓库实际路径 REPOS=( "/home/you/projects/repo-a" "/home/you/projects/repo-b" "/home/you/projects/repo-c" ) for repo in "${REPOS[@]}"; do if [ -d "$repo/.git" ]; then BRANCH=$(git -C "$repo" rev-parse --abbrev-ref HEAD) echo "$repo: $BRANCH" else echo "$repo: 不是有效的Git仓库" fi done
- 给脚本添加执行权限:
chmod +x check_branches.sh
- 运行脚本:
./check_branches.sh
这样就能一次性输出所有指定仓库的当前分支,无需逐个切换目录。
内容的提问来源于stack exchange,提问作者abbood
相关产品推荐
相关产品推荐

