Skip to content

Instantly share code, notes, and snippets.

@Iksas
Last active October 31, 2025 10:58
Show Gist options
  • Save Iksas/90c9d9ed7329394bd3c10137931eb415 to your computer and use it in GitHub Desktop.
Save Iksas/90c9d9ed7329394bd3c10137931eb415 to your computer and use it in GitHub Desktop.
git cheat sheet

Git cheat sheet

Editing

  • Remove last commit

    git reset HEAD^

  • Interactive rebase onto origin

    git rebase -i origin

  • Staging only parts of a file

    • edit the diff before adding it to the staging area: git add -e <filename>
    • quickly stage individual hunks: git add --patch <file>
  • Combine the last two commits into a single commit:

    git rebase -i HEAD~2

  • Pull branch main from a different repo, and rebase the current branch on top of it:

    git pull --rebase https://example.com/test.git main

  • Check out only a certain subfolder:

    • git clone -n --depth=1 --filter=tree:0 https://example.com/test.git
    • cd test
    • git sparse-checkout set --no-cone /subfolder
    • git checkout
  • Add changes to the second-to-last commit:

    • Create a new commit containing the changes
    • Rebase the last three commits: git rebase -i HEAD~3
    • Move the new commit up until it's directly below the commit that the changes should be added to
    • On the new commit, replace pick with fixup
    • Save and exit the text editor

Gathering information

  • Search the reflog for info about a commit (only works if the relevant info hasn't been garbage-collected):

    git reflog --no-abbrev | grep <HASH>

  • List the number of lines in each file:

    git ls-files | xargs wc -l

  • Count the number of lines of all Python files

    git ls-files | grep \\.py$ | xargs wc -l

  • Search the code for a certain string. The oldest commit containing the string is listed first:

    git log --all -p --reverse --source -S "string"

    git --no-pager log --all -p --reverse --source -S "string"

Useful links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment