hisham hm

Git Cheat Sheet

I have a hard time memorizing certain unfrequent tasks on Git. I’ll write them down here as I learn them so I can look it up later.

Undo a commit

If you just made a commit (perhaps typing git commit -a too eagerly) and realize you made a mistake, use this to uncommit the modified code, so it shows as “modified:” in git status again and appears again in git diff:

git reset HEAD~

I even added an alias git undo-commit, like this:

git config --global alias.undo-commit 'reset HEAD~'

Getting the last commit from another branch

When working in an alternative branch, you can retrieve the latest commit from another branch with this:

git cherry-pick other-branch

Example:

$ git checkout anotherBranch
$ git branch
* anotherBranch
  master
$ edit some files...
$ git commit -a
$ git checkout master
$ git branch
  anotherBranch
* master
$ git cherry-pick anotherBranch

Interactively select which edits should be committed

After making several edits across files, sometimes you want to add them as separate commits. Committing files separately is easy, but sometimes various edits in the same file should be different commits (or some changes to a file are ready to be committed but others are not). To commit part of the changes to a file, use:

git add -p

From the manual:

“Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index. This effectively runs add –interactive, but bypasses the initial command menu and directly jumps to the patch subcommand.”