Having used Git for a good few years now, over time I have aquired a list of Git commands. Some very frequent and used daily. Other’s not so much. But, on a certain occasion and the “uh-oh” moment, I find them rather useful to get me out of a pickle.
So I thought I should share some common Git commands I use.
If you’re new to Git, I found Atlassian’s Git a good start and provides a very good foundation and understanding.
Branching in Git
Create a local branch from the current branch you are on and switch to this new branch immediately.
git checkout -b <branch>
Example
git checkout -b mybranch
Switch to a branch.
git checkout <branch-name>
Pushing in Git
Push local branch to a remote repository when the branch doesn’t exist on the remote repository.
git push -u origin <branch>
Push local branches to a remote repository when the branch already exists on the remote repository.
git push
Checking Status
Check the current status of the branch, including files added, edited, deleted and the branch name.
git status
Merging
Merges the named branch into the current branch.
git merge <branch-name>
Getting latest
Download and get latest changes from a remote repository. E.g. if new branches were created, these will be downloaded as well.
git fetch
Downloads latest changes from a remote repository and merges them to the current branch.
git pull
What’s the difference between git fetch
and git pull
? According to the StackOverflow answer on what is the difference between git pull and git fetch, git pull is performs a git fetch
followed by a git merge
.
Aborting a Git Merge
When performing a git pull
or a git merge
and things have gone a bit sideways, you can always abort.
git merge --abort
When git merge --abort
doesn’t work. You can try to use git reset
.
git reset --merge
git reset --hard HEAD
Aborting a Git Rebase
When a git rebase
has gone sideways. You can abort using the following command.
git rebase --abort
Undoing or reverting a local commit
If local commits have not been pushed to the remote repository, they can be reverted.
If you know the commit id, you can use the reset command
git reset --hard HEAD <commit-id>
Example if the commit id is be20eb8
, then to revert this commit, the command is:
git reset --hard be20eb8
This will revert the commit be20eb8
Or, if you know the number of commits, you can use this.
git reset --hard HEAD~<n>
Where n
is the number of last commits you want to revert
Example
git reset --hard HEAD~1
This will revert the last commit.
git reset --soft HEAD~1
This will rever the last commit, but keep the last commit changes.
Hope you found this useful and if I ever discover any new useful Git commands, I’ll be sure to add to this post.