Skip to content

Git Notes

https://learngitbranching.js.org/

Reference a Commit

  • HEAD current commit
  • ru49uh commit hash
  • HEAD^^^ 3 commits before HEAD
  • HEAD~3 3 commits before HEAD
  • use tag name
  • git checkout <commit-ref> point HEAD to commit

Branch

  • git checkout -b <branch-name> create and switch to branch
  • git checkout <branch-name> switch to branch
  • git branch -f <branch-name> <commit-ref> point <branch-name> to <commit-ref>, useful when HEAD is detached
  • git branch -u <remote-branch-name> set current branch to track <remote-branch-name>

Merge

  • git merge <branch-name> merge <branch-name> to current branch

Rebase

  • git rebase <branch-name> rebase current branch to <branch-name>
  • git rebase -i <commit-ref> rebase interactively every commit after <commit-ref>, and point the branch to the last commit after rebase
  • never rebase a public branch

Reverse Changes

  • git reset HEAD~1 (only if not pushed to repo) reverse the branch to one commit before HEAD
  • git revert HEAD add a commit that reverse the change made in HEAD

Cherry Pick

  • git cherry-pick <commit-ref> ... copy commits to the current branch

Change a Commit

  • git commit --amend amend changes to last commit

Tag

  • git tag <tag-name> <commit-ref> add tag <tag-name> to <commit-ref>

Others

  • git remote set-url origin <url> change remote url

Working with Remote Repos

  • when checking out a remote branch (e.g. origin/master), git will automatically detach HEAD
  • git fetch update the remote branch (stored locally to track commits on the remote server) to match commits on the remote server
  • git pull = git fetch + merge remote branch just fetched to the local branch
    • git pull --rebase to rebase on remote branch instead of merging
  • git push upload commits in current branch to remote server
    • git push origin <branch-name>

Last update: March 29, 2021
Created: March 25, 2021