Useful Git Commands
Just documenting some useful git commands that I use occasionally. This list is hopefully being extended over time :-)
Basic commands
List all branches:
git branch -a
Get remote url:
git config --get remote.origin.url
Switch to branch:
git checkout branch_name
Create a new branch and push to remote:
git checkout -b new_branch_name
git push -u origin new_branch_name
Create a new branch and switch to it:
git checkout -b new_branch_name
Reset local git back to a specific commit.
git reset --hard <commit id>
And force push it back:
git push origin master -f
Count lines of code (of e.g., *.go files):
git ls-files | grep go | xargs wc -l
Adding upstream to a fork
Our branch is named master
, the origin of our fork is named upstream
.
git remote add upstream https://github.com/USER/REPO.git
git fetch --all # fetch from remote (or git remote update)
git branch -v -a # to see branches
git checkout master # make sure to be on master
git rebase upstream/master # rebase upstream on our master branch
git push -f origin master # push new commits to our remote
Cherry pick a commit for a pull request:
git checkout -b upstream upstream/master
git cherry-pick <SHA hash of commit>
git push origin upstream
Submodules
Adding a submodule:
git submodule add https://github.com/USER/REPONAME.git ./REPONAME
Cloning including all submodules:
git clone --recursive https://github.com/USER/REPONAME.git
Remove a submodule:
git rm --cached PATH/TO/SUBMODULE
Then:
- Remove the relevant lines from
.gitmodules
- Remove the relevant lines from
.git/config
- Commit.
- Delete local files.
- Remove
.git/modules/SUBMODULE