Git Tricks

Reminders to self.

Multiline Commit Messages

The commit command accepts multiple -m flags:

$ git commit -m "Commit title" -m "A new paragraph."

Each use adds a new paragraph to the commit message. A similar effect can be achieved using quotes:

$ git commit -m "Commit title
> A new paragraph."

If you belatedly decide that you should have used an editor after all you can pass the -e flag to open your editor with the partially-complete message intact:

$ git commit -m "Commit title" -m "Now I want an editor..." -e

List Aliases

Adding this snippet to your .gitconfig file creates a git alias command which lists all registered aliases:

    alias = !git config --list | grep alias | sed s/^alias.//

The Missing 'Amend' Command

Write a commit message, hit return, instantly notice the typo...

The fix is to run:

$ git commit --amend

This opens the last commit message in your editor, allowing you to rewrite it. I do this often enough that I've added the following alias to my .gitconfig file:

    amend = commit --amend

This way I can run git amend instead.

Discard All Changes

Discard all changes in the working directory — i.e. restore its state to that at the last commit — by running:

$ git checkout -f

Squashing Commits

To squash the last N commits together:

git reset --soft HEAD~N
git commit

To squash all the commits after <commit>:

git reset --soft <commit>
git commit

Here <commit> can be a branch or tag name or a commit hash.

Merging Commits

To merge commits from branch main into branch feature:

git checkout feature
git merge main

This will create a merge commit.

To merge commits from branch feature into branch main, squashing all the commits into a single commit:

git checkout main
git merge --squash feature
git commit

The commit message will be pre-populated with a default message describing the squashed commits.

Rebasing Commits

To rebase branch feature on top of branch main:

git checkout feature
git rebase main

Refresh Remote Branches

To list all local and (known) remote branches:

git branch --all

To update the local list of remote branches, pruning branches that no longer exist:

git remote update origin --prune

To automatically prune the local list of remote branches every time git fetch or git pull runs:

git config remote.origin.prune true

Push New Local Branch

To push a new local branch to a remote repository:

# Create a new local branch, 'feature'.
git checkout -b feature

# Push the new local branch to 'origin'.
git push -u origin feature

The -u/--set-upstream flag tells the local branch to track the new remote branch.

Undo Last Commit

Undo the last commit, leaving the files in the working directory unchanged:

git reset --soft HEAD~1

Undo the last commit, resetting the state of the working directory:

git reset --hard HEAD~1

Show Changes

Show the changes made in the most recent commit:

git show

Show the changes made in a particular commit:

git show <commit>