I'm working on a bash script for my team to enforce regular rebasing of working branches. The problem I am facing at the moment is how to determine whether a branch is behind master and/or if it needs to be rebased, rather than blindly attempting to rebase the branch.
Here is a simplified version of what I have so far:
#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
Any ideas would be much appreciated. Thanks!
Unless your code has changed drastically, if the merge results in no change, then the branch has been rebased already. Otherwise, it obviously has not.
Checkout to the desired branch you want to rebase. Now perform the rebase command as follows: Syntax: $git rebase <branch name>
1 Answer. Show activity on this post. Case 1: We should not do Rebase on branch that is public, i.e. if you are not alone working on that branch and branch exists locally as well as remotely rebasing is not a good choice on such branches and it can cause bubble commits.
Rebasing a branch in Git is a way to move the entirety of a branch to another point in the tree. The simplest example is moving a branch further up in the tree. Say we have a branch that diverged from the master branch at point A: /o-----o---o--o-----o--------- branch --o-o--A--o---o---o---o----o--o-o-o--- master.
To tell if you need to rebase your branch, you need to find out what the latest commit is and what was the last commit that your two branches share.
To find the latest commit on the branch:
git show-ref --heads -s <branch name>
Then to find the last commit that your branches have in common:
git merge-base <branch 1> <branch 2>
Now all you need to do is find out if these two commits are the same commit. If they are, then you don't need to rebase. If they are not, a rebase is required.
Example:
hash1=$(git show-ref --heads -s master)
hash2=$(git merge-base master foo/bar)
[ "${hash1}" = "${hash2}" ] && echo "OK" || echo "Rebase is required"
Though as stated in the comment, if you attempt to rebase a branch that is already up to date. Git will gracefully handle the situation and exit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With