git - 如果 git 中的分支需要 rebase ,如何务实地检查 bash 脚本?

标签 git bash rebase git-rebase git-bash

我正在为我的团队编写一个 bash 脚本,以强制对工作分支进行定期 rebase 。我现在面临的问题是如何确定一个分支是否落后于 master 和/或它是否需要 rebase ,而不是盲目地尝试 rebase 分支。

这是我目前所拥有内容的简化版本:

#Process each repo in the working directory.
for repo_dir in $(ls -1); do
    # if working branch is clean ...

        # BEGIN update of local master
        git checkout master
        git fetch origin
        git merge remotes/origin/master
        # END update of local master

        for sync_branch in $(git branch | cut -c 3-); do
            if [ "$sync_branch" != "master" ]; then
                # BEGIN rebase working branch
                git checkout $sync_branch
                git rebase master
                # Do NOT push working branch to remote.
                # END rebase working branch
            fi
        done
    fi
done

任何想法将不胜感激。谢谢!

最佳答案

要判断您是否需要 rebase 您的分支,您需要找出最新的提交是什么以及您的两个分支共享的最后一次提交是什么。

查找分支上的最新提交:

git show-ref --heads -s <branch name>

然后找到你的分支有共同的最后一次提交:

git merge-base <branch 1> <branch 2>

现在您需要做的就是找出这两个提交是否是同一个提交。如果是,那么您不需要重新设置基准。如果不是,则需要进行 rebase 。

例子:

hash1=$(git show-ref --heads -s master)
hash2=$(git merge-base master foo/bar)
[ "${hash1}" = "${hash2}" ] && echo "OK" || echo "Rebase is required"

尽管如评论中所述,如果您尝试重新设置已经是最新的分支。 Git 将优雅地处理这种情况并退出。

关于git - 如果 git 中的分支需要 rebase ,如何务实地检查 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30177047/

相关文章:

c - 在自定义 shell 中编写用于输入/输出文件重定向的命令

linux - 在函数中维护变量——全局变量

shell - .bashrc、.bash_profile 和 .environment 之间有什么区别?

version-control - Mercurial 功能工作 - 保持定制工作干净的最佳实践?

Git 凭据帮助程序不适用于 linux 的 Windows 子系统

git - 假删除 Git 中的文件

git - 如何防止 OpenSSH 关于主机 key 攻击的警告?

git - 如何防止删除纯 GIT 中的远程分支

git - 是否可以在不使用交互式 rebase 的情况下 rebase 和编辑 git 提交?

git - merge --squash 和 rebase 有什么区别?