Some handy git commands
29 March 2015 · git TweetMan, I haven't blogged in a long time! I don't have any particular excuse for that :| So I'm gonna try and write a random post in order to start again, and try to blog frequently.
These are some git commands I found useful in the past two months of contributing to open source.
- You don't wanna work on the master branch. Actually, I made that mistake; made some changes, pushed them and opened a PR. In order to solve another issue, I made more changes, pushed them and found that they added up to the earlier PR :| Well, I had "heard" of branching but never really tried it.
$> git checkout -b branch-name $> git add . $> git commit -m "Commit message" $> git push origin branch-name
You can see all your branches with git branch -l
. After your PR is merged, you can remove that branch with git branch -D branch-name.
Protip: Branch out from master
. Visualize trees (Referring to the data structure).
- Suppose you wrote a non-informative commit message in a hurry and pushed that commit, it could be solved by
git commit --amend
which lets you fix the most recent commit.
$> git commit --amend $> git push -f origin branch-name
- When you're working on some issue for a different project and have pushed many commits in your branch, the history gets flooded with your commits and doesn't look nice. You can squash all those commits (last n) together into a single commit.
$> git rebase -i HEAD~n # Change pick to squash for a all n-1 commits except # the first one in the text editor, save and exit. $> git push -f origin branch-name
- To revert the status of a branch to a specific commit, get that commit's SHA-1 hash from
git log
.
git reset --hard hash
- When there are unfinished changes in a branch, and you want to change into a different branch, you can stash the unfinished changes.
$> git stash $> git stash list stash@{0}: WIP on rename_LDA_QDA: d09f7f7 Removed ... stash@{1}: WIP on RFECV: 4a57c92 Merge pull request ...
git stash apply
will apply the most recent stash on the working branch. git stash pop
will apply the most recent stash and delete it from the list. A specific stash can be applied using git stash apply stash@{n}
.
git stash drop stash@{n}
will delete that stash from the list.
- I've never really done cherry-picking, but I hear that it can be quite useful.
Suppose you are on the master branch and want only a specific commit from another branch without merging that branch, you can cherry-pick that commit using its SHA-1 hash.
git cherry-pick hash
I will add to this list when I come across more useful commands!