I use the git cli every single day for my source code management needs. Sometimes I forget how to do certain things with git or I just haven’t automated it yet, so I’m writing it all down so that I have something to easily refer to:

Squash all commits on a branch

git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD))


Get the number of commits added to your branch

git rev-list --count master..


Squash and merge your X latest commits

git reset --soft HEAD~3 && 
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"


Create a repo on GitHub

gh repo create <name> --private

Merging in a branch with lots of commits without a merge commit

git merge --squash v1.0
git commit

Delete a remote branch

git push origin --delete branch-name

Delete local branch

git branch -D branch-name

Show diff of last commit

git show

Undo a git add

git reset <file>


Undo changes to a single file

git checkout <file>


Undo changes to all unstaged files

This was the initial way I removed all my unstaged files:

git diff --name-only | xargs -n1 git checkout

but a much better way is:

git restore .


Create a PR

gh pr create --fill

Fetch a remote branch

I often have my own remote separate from origin that I need to pull a branch from.

git fetch <remote> <rbranch>:<lbranch>
git checkout <lbranch>


Change/Amend last commit message

Sometimes you notice a typo in your commit message after generating a PR or looking at it on GitHub. If it’s not too late you can fix your commit message and then force push it up.

git commit --amend
1 Like