Stashing part of your changes with git

Do you ever run into that situation while coding where you need to temporarily undo some of your uncommitted changes? I sure do.

If you are a git user you have likely used git’s stash feature, this allows you to park changes that you have made rather than committing them. If you didn’t know already: you can even stash new files if you stage them first (using the git add command).

If you want to stash changes to specific files rather than all your changes you can use the push sub-command like shown in the below example:

$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   README.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        FILE1.txt
        FILE2.txt
        FILE3.txt

no changes added to commit (use "git add" and/or "git commit -a")
$ git add .
$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   FILE1.txt
        new file:   FILE2.txt
        new file:   FILE3.txt
        modified:   README.txt

$ git stash push README.txt FILE1.txt
Saved working directory and index state WIP on trunk: d2bcd85 Initial commit
$ git status
On branch trunk
Your branch is up to date with 'origin/trunk'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   FILE2.txt
        new file:   FILE3.txt

Restoring your stashed changes works as it normally would (using git stash pop).