Git tips

Amending the most recent commit message

git commit --amend

This command will open your editor, allowing you to change the commit message of the most recent commit.
Additionally, you can set the commit message directly in the command line with:

git commit --amend -m "New commit message"

However, this can make multi-line commit messages or small corrections more cumbersome to enter.

Changing git commit message after push

After amending the most recent commit, do this:

git push --force-with-lease [<repository>] [<branch>]

Or you can use "+":

git push <repository> +<branch>

Or you can force it:

git push -f|--force [<repository>] [<branch>]

Be careful when using these commands.

  • If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The --force-with-lease option is the safest, because it will abort if there are any upstream changes.
  • If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time.

Pulling / fetching afterwards

Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:

git fetch origin
git reset --hard [<repository>/<branch>] # Loses local commits

Be careful when using reset --hard. If you have changes to the branch, those changes will be destroyed.

Undo the last commit

git reset HEAD~|HEAD^

This leaves your working tree (the state of your files on disk) unchanged but undoes the commit and leaves the changes you committed unstaged (so they'll appear as "Changes not staged for commit" in git status and you'll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message, you could use git reset --soft HEAD~ instead, which is like git reset HEAD~ but leaves your existing changes staged.

Rolling back local and remote git repository

If nobody has pulled your remote repo yet, you can change your branch HEAD and force push it to said remote repo:

git reset --hard HEAD~|HEAD^
git push -f|--force

When somebody has already pulled the repo

git revert HEAD~|HEAD^
git push

Revert the changes specified by the last commit in HEAD and create a new commit with the reverted changes.

Setting paths

Set the path to the repository and the working tree:

git --git-dir=/path/to/repo.git --work-tree=/path/to/working-dir ...

These can also be controlled by setting the GIT_DIR and GIT_WORK_TREE environment variables.