Quick Git Tip ... Quickly Merging Changes From Your Local Branch
For most of my work, I’m the only developer. That means that, up until now, I’ve mostly just worked in a master branch of my code, and haven’t utilized branches in Git.
But I’m eager to get better at using Git, so I’ve started creating branches for feature pushes. I create the branch, jump into it, make my changes, commit them, jump back to ‘master’, merge the changes, push them to the main repo at GitHub, and jump back to my branch to make more changes.
The problem? That’s a lot of steps.
Just so the steps are clear: After you’ve made your commits (to, say, a branch called “popups”) and are ready to push your repo to GitHub you have to type:
git checkout master
git merge popups
git push
git checkout popups
Even with shortcuts and aliases, it’s a number of unnecessary steps. They’re cumbersome, especially since nobody else is pushing code to this repository, so I don’t have to worry about conflicts with other peoples’ code. Apart from the branch name, my code to push it to GitHub looked identical every single time.
I wanted a way to reduce the process down to one simple shortcut. I asked for help on Twitter and got comments from Jared and Ken, and was able to put together a quick bash script.
If you add the following line to your .bash_profile
, you’ll execute the four lines above (obviously, intelligently handling the name of the active branch) just by typing in gpm
in your Terminal:
alias gpm=”temp=$(git branch 2> /dev/null | grep ‘^*’ | sed ‘s/^*\ //’); git checkout master; git merge $temp; git push; git checkout $temp;” # mnemonic: git push master</span> |
Update: Actually, I found a better option. This puts the work into an external bash script, which looks like this:
ref=$(git symbolic-ref HEAD 2> /dev/null) || exit 0
CURRENT="${ref#refs/heads/}"
git checkout master
git merge ${CURRENT}
git push origin master
git checkout ${CURRENT}
I save that in my root folder, as .ship
(so total path: ~/.ship
).
Then, I alias that in my .bash_profile
as alias gpm="sh ~/.ship"
and I’m good to go.
Obviously, if you’re on a team, you’ll want to make sure you’re up to date before you push to the remote origin/master, but if you’re working solo like me, this helps cut down the friction on using Git more efficiently.
And if you want a bunch of other shortcuts that do far more than mine, check out Ken’s shell commands, posted as a gist at GitHub.