All articles

Infra15 min read

Git made simple: stash, amend, fetch, rebase and reflog

Git without fear: git stash, git mv, commit --amend, fetch vs pull, rebase vs merge, interactive rebase, push --force-with-lease and reflog to undo almost anything.

Also in Português, Español, Français

Are you scared of Git? Is git add, git commit and git push as far as you go, and every other command makes you nervous? You're not alone.

Git looks intimidating because almost every command touches a different place, and nobody shows you the map. Once you understand where each command acts, it stops being a monster and becomes a tool that saves you every week.

I first published this post on Medium in 2023, in Portuguese. This is the revised version: better explanations, a few of my own mistakes fixed, and every command tested again.

Here I explain the commands I use most beyond commit and push, with examples I actually ran in a test repository: git stash, git mv, git commit --amend, git fetch, git rebase (including interactive) and, at the end, git reflog, which undoes almost any mistake.

TL;DR#

  • git stash puts your uncommitted changes in a drawer, and git stash pop brings them back. New files only go in with -u.
  • git mv is a shortcut for mv + git add. Git doesn't store renames: it infers them from the content. To see the history of a renamed file, use git log --follow.
  • git commit --amend replaces the last commit with a new one. Great for a forgotten file or a bad message, as long as the commit hasn't been pushed.
  • git fetch only downloads and updates origin/main. It doesn't touch your code. git pull is fetch + merge (or rebase).
  • git rebase replays your commits on top of another base and keeps history in a straight line. Interactive mode (-i) squashes, edits and reorders commits.
  • Rewrote history that was already pushed? Use git push --force-with-lease, never --force (or +branch). In my test, +main deleted a colleague's commit without a warning.
  • Something went wrong? git reflog lists everywhere your HEAD has been, and git reset --hard HEAD@{n} takes you back.

The map: where each command acts#

Before the commands, the drawing that made Git click for me. There are five places, and each command moves changes from one to another:

  1. Working directory: the files you edit.
  2. Stash: a drawer to keep changes without committing.
  3. Index (or staging): what goes into the next commit, after git add.
  4. Local repository: your commits, on your machine.
  5. Remote: GitHub (or GitLab, Bitbucket). Your machine keeps a copy of what it last saw there, origin/main.
Each command moves changes from one place to another. fetch stops at origin/main

Keep this map in mind. Almost every Git mix-up comes from thinking a command acts in one place when it acts in another.

git stash: the drawer#

You're in the middle of a task, with modified files, and you need to switch branches to fix an urgent bug. Committing half-done work is ugly. git stash puts the changes in a drawer and leaves the directory clean:

git stash push -m "wip: signup form"
git switch hotfix/login
# ...fix the bug, commit, push...
git switch feature/signup
git stash pop

A detail that catches a lot of people: a new file, one Git doesn't track yet, doesn't go into the drawer. In my test, after git stash, the new file was still there:

$ git stash push -m "wip: signup form"
Saved working directory and index state On main: wip: signup form
$ git status --short
?? draft.txt

To take new files along, use -u (short for --include-untracked):

git stash push -u -m "wip: signup form"

The git stash save "name" you see in old tutorials is deprecated. The current way to name a stash is git stash push -m "name".

pop or apply?#

Both bring the changes from the drawer back to the working directory. The difference is what happens to the drawer:

  • git stash apply applies and keeps the stash in the list. Useful to apply the same change to more than one branch.
  • git stash pop applies and deletes the stash from the list. It's apply followed by git stash drop.

With one exception: if pop hits a conflict, it deletes nothing. Git tells you so:

Auto-merging app.txt
CONFLICT (content): Merge conflict in app.txt
...
The stash entry is kept in case you need it again.

You resolve the conflict, then delete the stash with git stash drop once you're sure you don't need it anymore.

Other drawer commands:

git stash list              # every stash, newest first: stash@{0}, stash@{1}...
git stash show -p stash@{1} # what is inside one of them
git stash pop stash@{1}     # bring back a specific one
git stash drop stash@{1}    # delete one

git mv: rename and move#

git mv renames or moves a file and stages the change for the commit:

git mv index.html home.html     # rename
git mv index.html public/       # move
git mv scripts src/scripts      # folders too

The first version of this post said git mv exists so you "don't lose history". I believed that too, and it's not quite right. Git doesn't store renames. It stores the content of the files in each commit and, when it shows you the history, it compares: if one file disappeared and another almost identical one appeared, it concludes the file was renamed.

That's why mv + git add -A gives exactly the same result. I tested both, and git status shows the same thing:

$ git mv index.html home.html
$ git status --short
R  index.html -> home.html
 
$ mv home.html start.html && git add -A
$ git status --short
R  home.html -> start.html

The R is Git saying "I detected a rename". git mv just saves you a step.

What about history? A file's git log stops at the rename. To follow the file through its old names, use --follow:

$ git log --oneline -- home.html
3b727de rename index to home
 
$ git log --oneline --follow -- home.html
3b727de rename index to home
a366c0e add index page

Tip: rename in one commit and change the content in another. If you rename and rewrite half the file in the same commit, Git may not recognize it as the same file, and then not even --follow finds the history.

Changed your mind before committing? Just rename it back with git mv home.html index.html.

git commit --amend: fix the last commit#

"git amend" isn't a command. What exists is the --amend option of git commit, which replaces the last commit with a new one.

Forgot a file:

git add forgotten-file.ts
git commit --amend --no-edit   # same message, new content

Wrong message:

git commit --amend -m "feat: rename the home page"

What few people notice is that the commit isn't edited, it's replaced. Look at the hash changing with each --amend in my test:

22b393b rename again                  # before
f5024f2 rename again                  # after --amend --no-edit
4c2a0e4 feat: rename the home page    # after --amend -m

Hence the rule: only use --amend on a commit that hasn't been pushed. If it's already on the remote and someone pulled it, you'll need a force push (more on that at the end) and that person will be left with a commit that no longer exists.

git fetch: look before you bring it in#

git fetch downloads what's new on the remote and updates origin/main, that copy of the remote that lives on your machine. It doesn't touch your branch or your files. It's like reading the headlines without opening the newspaper.

$ git fetch origin
From ../origin
   4c2a0e4..8d7de9d  main       -> origin/main
 
$ git status -sb
## main...origin/main [behind 1]
 
$ git log --oneline main..origin/main
8d7de9d feat: add the profile page

main..origin/main lists the commits that are on the remote and not yet on your main. You see what arrived before deciding to bring it in.

fetch only updates origin/main. pull fetches and merges into your branch right away

And git pull? It's fetch followed by a merge (or a rebase, if you configure it). It downloads and merges into your branch, all at once:

git pull               # fetch + merge
git pull --rebase      # fetch + rebase

I prefer to fetch first when the branch is shared or when I haven't updated in days. I get to see how big the change is before the conflicts hit me in the face.

Bringing in changes from another repository#

fetch works with any remote, not just origin. Example: you have a fork and want the news from the original project. Add it as a second remote:

git remote add upstream https://github.com/original-author/project.git
git fetch upstream
git merge upstream/main

upstream is just a nickname, like origin. Then you resolve the conflicts (if any), commit and push to your fork.

git rebase: replay your commits on another base#

You created a branch, made two commits, and meanwhile someone pushed a new commit to main. To bring in what landed on main, there are two ways:

  • git merge creates a merge commit that joins the two histories. Nothing is rewritten.
  • git rebase takes your commits and replays them one by one on top of the new main, as if you had started the branch now. History stays in a straight line.
Merge joins the two histories. Rebase replays your commits, with new hashes

In my test, my local main had two commits origin/main didn't have, and origin/main had one I didn't have:

* 0df7909 wip
* 6f1f89e add z
| * 8d7de9d feat: add the profile page   (origin/main)
|/
* 4c2a0e4 feat: rename the home page

After git rebase origin/main:

* 2b2bea3 wip
* 4f1c163 add z
* 8d7de9d feat: add the profile page
* 4c2a0e4 feat: rename the home page

My two commits moved up, in a straight line, with new hashes (0df7909 became 2b2bea3). That's the key point about rebase: it doesn't move commits, it creates new commits with the same content.

Which one should you use? Neither is better, and many teams pick one as the default. The rule that matters is just one: don't rebase commits other people have already pulled. On your own branch, before opening the PR, go ahead.

Interactive rebase: tidy up the commits before the PR#

git rebase -i opens a list of the commits and lets you say what to do with each one:

git rebase -i HEAD~3   # the last 3 commits
pick 4f1c163 # add z
pick 2b2bea3 # wip
pick 060be7b # fix typo
 
# Rebase 8d7de9d..060be7b onto 8d7de9d (3 commands)

Below this list, Git itself explains the commands. The ones I use most:

  • pick: keeps the commit as it is.
  • reword: keeps it, but opens the editor so you can change the message.
  • edit: stops at this commit so you can change whatever you want (files, author), then git rebase --continue.
  • squash: melds it into the commit above and combines the messages.
  • fixup: melds it into the commit above and drops this one's message.
  • drop: deletes the commit.

You change the word at the start of each line, save and close. To fold wip and fix typo into the commit above, for example:

pick 4f1c163 # add z
fixup 2b2bea3 # wip
fixup 060be7b # fix typo

To edit several messages, change pick to reword. Git stops at each one and opens the editor.

If the editor doesn't open (or Vim opens and you don't know how to quit), set VS Code:

git config --global core.editor "code --wait"

--wait makes Git wait until you close the tab before moving on.

Commits with the wrong name or e-mail#

A classic on a new computer: you forgot to set user.name and user.email, and your commits went out as root@localhost. First, set them:

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

Then, to fix only the last commit:

git commit --amend --no-edit --reset-author

To fix several, instead of marking each one as edit like I used to, use --exec, which runs a command after each replayed commit:

git rebase origin/main --exec "git commit --amend --no-edit --reset-author"

Notice origin/main instead of HEAD~10. It picks only the commits that aren't on the remote yet, in other words, only yours. In my test, I used HEAD~2 and one of the two was a colleague's commit that was already on the remote. The rebase swapped its author for mine without asking. Counting commits with HEAD~n is easy to get wrong. Using the right base isn't.

Force pushing without wiping out other people's work#

Every command that rewrites history (--amend, rebase) creates new commits. If the old ones were already on the remote, a normal git push is rejected, because the remote would have to throw commits away. That's where force pushing comes in.

The first version of this post suggested git push origin +branch-name. The + does the same as --force: it overwrites the remote with your version, without checking what's there. I tested it: a colleague pushed a commit to the branch while I was rewriting mine. With +main, the push went through, and her commit vanished from the remote:

$ git push origin +main
 + c0a4ca7...db2256b main -> main (forced update)

With --force-with-lease, the same push was rejected:

$ git push --force-with-lease origin main
 ! [rejected]        main -> main (stale info)
error: failed to push some refs to '../origin.git'
--force-with-lease only overwrites if the remote is still the way you last saw it

--force-with-lease only overwrites if the remote is still the same as the last version you saw (your origin/main). If someone pushed something in the meantime, it refuses, and you git fetch, bring in that person's commit and try again.

One caveat: if you run git fetch right before, your origin/main is already up to date, and the lease lets the push through even though you never incorporated that person's commit. To close that hole there's --force-if-includes, which checks that what's on the remote is also in your branch. I tested it: after a git fetch, --force-with-lease alone ran over the colleague's new commit, and with --force-if-includes added the push was rejected:

$ git push --force-with-lease --force-if-includes origin main
 ! [rejected]        main -> main (remote ref updated since checkout)

An alias saves you typing this every time:

git config --global alias.pushf "push --force-with-lease --force-if-includes"
git pushf

And the usual rule: force pushing to your own branch is fine. On a shared main, agree with the team first (or keep main protected on GitHub).

git reflog: Git's undo#

A rebase went wrong? A reset --hard in the wrong place? Relax. Almost nothing is truly lost in Git. git reflog keeps every place your HEAD has been, including commits that no longer show up in git log:

$ git reflog -6
9eadb5e HEAD@{0}: rebase (finish): returning to refs/heads/main
9eadb5e HEAD@{1}: commit (amend): add z
3a8f3fa HEAD@{2}: rebase (pick): add z
f7db88b HEAD@{3}: commit (amend): feat: add the profile page
8d7de9d HEAD@{4}: rebase (start): checkout HEAD~2
fba2c8f HEAD@{5}: rebase (finish): returning to refs/heads/main

That's how I undid the rebase that changed the author of my colleague's commit. HEAD@{5} was the state before it, so:

git reset --hard HEAD@{5}

And everything went back to how it was. Before any operation that scares you, you can also create a safety branch, which costs nothing:

git branch backup/before-rebase

If things go wrong, the branch is there, pointing at the commit from before.

The reflog is local and not forever: by default, entries for commits that aren't on any branch expire after 30 days. And changes that were never committed or stashed are something the reflog can't save.

Cheat sheet for next to your monitor#

I want to...Command
Put away uncommitted work and clean the directorygit stash push -u -m "name"
Bring it back from the drawergit stash pop
Rename a filegit mv old new
See the history of a renamed filegit log --follow -- file
Add a forgotten file to the last commitgit add file && git commit --amend --no-edit
See what arrived on the remote, without touching anythinggit fetch && git log main..origin/main
Update my branch in a straight linegit rebase origin/main
Squash or edit commits before the PRgit rebase -i origin/main
Push rewritten history without wiping anyone else'sgit push --force-with-lease
Undo a messgit reflog and git reset --hard HEAD@{n}

Conclusion#

See? It's not a monster after all. Once you see the five places (working directory, stash, index, local repository and remote), each command is just an arrow between them. And with reflog in your pocket, mistakes stop being scary, because almost everything can be undone.

Want to practice without risk? Create a folder, run git init and go through every example in this post there. That's how I tested every command here.

References#

  • Infra
  • git
  • terminal
  • rebase
  • version control
  • productivity

Written by

Software engineer and designer. I write about what I run into while building apps, APIs and products.