Useful git commands while working on
As a developer many of us use git for version control. Here I’m listing most common things I do while working on daily projects.
1- ) Merging a branch into current branch
Sometimes we need to merge a branch into our current branch and resolve some conflicts and push it back. It mainly occurs when we have seperate feature branchs and one of it merges into develop before ours.
Lets say we want to merge our develop branch into master. Our develop branch has a new commit different from master:
We checkout to branch master and merge develop into current branch.
git checkout master
git merge develop
We see now master synced with develop.
2 - ) Setting an upstream branch for a local branch
We use jira to track our issues, and we create branchs from inside an issue to link it together. Stash generate a name which related with issue title and assigsns it to created branch. But if we want to give another name to our local branch somehow we need to link it to remote branch.
git branch --set-upstream-to origin/branch-name
3 - ) Changing git remote url
I encountered this situation when I clone an open source project from github without forking it. I need to set origin url as my github fork.
git remote set-url origin https://github.com/USERNAME/REPOSITORY.git
4 - ) Rebase & Changing last commit message
We encounter a situation that we may want to change commit message of a previous commit. Once we learn rebase and amending, it is as simple as below.
git rebase -i HEAD~1
Git rebase -i opens interactive ui for us. We select the commit with changing pick to edit.
We type :wq for save and quit.
After that we type
git commit --amend
and it opens interactive ui. Change commit message from “secon commit” to “secon commit edited”
Again type :wq for save and quit.
When we finish our job we type:
git rebase --continue
And in commit history we see that our commit message and commit hash has been changed
When we rebase multiple commits, it creates a new commit. It causes to lost previous commit history.
5 - ) Reverting last commit
To revert last commit we have several options:
git reset --hard HEAD~1
In the above command, git reverts last commit but you need to be careful, it also discards uncommitted changes.
To prevent this, you can use the below comment to keep uncommitted changes.
git reset --soft HEAD~1
Example
Our current git repository has 2 commits
We change the file but not commit yet
If we want to revert commit dd5eedfef and do this while we have uncommitted changes, here what happens after hard reset
We lost the current uncommitted changes. But if we do same thing with soft reset
It resets the last commit and keep the changes.
To follow me on github: https://github.com/mstrYoda