Make your life easier with Git aliases
Table of Contents
If there is one tool I’m constantly using throughout the day, it must be Git! Since most of the commands I need are basically the same, I’ve created some Git aliases to reduce the number of keystrokes.
You can place these aliases in your ~/.gitconfig file, under the [alias] section. If you need project-specific overrides or aliases, you can put them in the .git/config file inside each repository too.
You can do this with a text editor or by using the git config --global alias.<name> "<command>" command.
Push current branch to the origin repository
This alias will push the branch you’re currently working in back to origin.
p = "!git push origin $(git rev-parse --abbrev-ref HEAD)"
If you want to push other branches besides the current one, you can add them as extra arguments. For example: git p master will push both the current working branch and your local master branch back.
Pull in latest changes for the current branch and rebase
Whenever I continue to work on a branch, I want to make sure I have the latest changes locally. This alias will pull in the latest changes for the current branch from origin and rebase my own local commits - if any - on top of them.
pu = "!git pull --rebase origin $(git rev-parse --abbrev-ref HEAD)"
Call with: git pu
Commit changes
Commit a little bit faster with this alias:
c = "!git commit -a -m "
Example usage: git c "My commit message"
Checkout a branch
Another short one, to checkout a different branch:
co = "!git checkout "
For example, checkout the feature/wip branch with git co feature/wip or create a new feature/new branch with git co -b feature/new.
Merge current branch into another one
On projects where we work with a staging or test branch, I regularly merge my work in progress into it so others can test it.
Because it’s not possible to pass arguments directly to a git alias, I’m using a function here (f()). That way I can chain multiple git commands. Here’s how what this alias looks like:
m = "!f() { CURBRANCH=$(git rev-parse --abbrev-ref HEAD); git co \"$1\" && git pu && git merge $CURBRANCH && git p && git co $CURBRANCH; }; f"
If you now type git m staging while on the feature/wip branch, this will happen:
- First, the function checks out the
stagingbranch. - It then pulls the latest changes to the
stagingbranch fromorigin. - Then it merges
feature/wipintostaging. - Next, it pushes the updated
stagingbranch back toorigin. - Finally, it checks out the
feature/wipbranch again.
Such a timesaver!
These examples are specific to the way I work but these should set you on your way to create your own!