skip to content
Alberto Mosconi
⇐ go back to all posts

Useful Git Commands

Some git commands I think are very useful:

update last local commit

In case you wish to change a commit that you haven't yet pushed to a remote repository you can easily change it.

If you made a typo writing the message you can fix it with the --amend flag.

git commit --amend -m "new message!"

If insted you forgot to add some files the --amend flag again can fix this. By including --no-edit the commit message will remain the same.

git add.
git commit --amend --no-edit

Check the documentation for more info: —amend.

override remote with local code

NOTE: this will cause all remote code that isn’t on your local machine to be lost!

git push origin main --force

Here I’m referencing the main branch but you can replace it with any branch.

undo remote commit

If you pushed a commit and later realized that it contained some problems, you can undo the changes with a new commit by using the revert command. This requires the working tree to be clean (no modifications to the HEAD commit).

git revert <commit>

Above, <commit> specifies which commit to revert. For a complete list of ways to spell commit names, see gitrevisions.

git revert HEAD   # undo latest
git revert HEAD~2 # undo third latest

Check the documentation for more info: git-revert.

save changes without committing

If you made a bunch of changes but you haven’t yet reached a point where they can be committed, you can use git stash to remove them from the working directory and save them for later use.

git stash # save changes
git pop   # add changes back

Additionally, you can give a name to your changes. This makes it easier when you want to stash more than once.

git stash save <name>

After naming, you can view all your named stashes with the list option.

git stash list

The output is an indexed list, showing each stash name and the corresponding number.

stash@{0}: On main: <first-name>
stash@{1}: On main: <second-name>

Using this number you can apply the stash to your current directory.

git stash apply <index>

Check the documentation for more info: git-stash.