Git Basics: Saving Unfinished Work with Stash
A stash temporarily sets aside local edits so you can return to a clean working tree. Practice saving and restoring one tracked file before using it during an interruption.
Run these commands in Bash with Git 2.28 or newer installed. Start a fresh temporary repository for this article:
git_practice=$(mktemp -d) || exit
cd "$git_practice" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThe identity and signing settings apply only to this repository. Use your own identity in real projects. The temporary files remain afterward. Examples assume default Git settings; if a pager opens, press q to leave it.
Prepare an unfinished edit
printf 'port=8080\n' > app.conf
git add app.conf
git commit -q -m 'Add application config'
printf 'port=9090\n' > app.conf
git status --short M app.confThe modification is in the working file and has not been staged.
Save it for later
git stash push -q -m 'Try another port'
cat app.conf
git stash list --format='%gd %s'port=8080
stash@{0} On main: Try another portThe working file is back at the committed value. stash@{0} names the newest stash. By default, stash saves changes to tracked files; untracked and ignored files are left alone. git stash push -u also includes untracked files, but still excludes ignored files.
Restore without removing the stash
git stash apply -q 'stash@{0}'
cat app.conf
git status --shortport=9090
M app.confapply restores the saved changes and keeps the stash entry. In this example the edit remains unstaged. Restoring the original staging state is a separate choice, using --index.
Applying to changed files can cause conflicts. Start with a clean working tree and inspect the result before deleting the stash. A stash is local temporary storage, not a backup uploaded to your remote.
Commit before removing the saved copy
git add app.conf
git commit -q -m 'Change application port'
git log -1 --format=%sChange application portThe edit is now safely in a commit. The next command deletes the selected stash entry; do not drop an entry until you have verified that you no longer need it.
git stash drop -q 'stash@{0}'
git stash listNo output means the stash list is empty. git stash pop combines applying with removal after a successful apply; using apply first gives you a chance to inspect the result.
Reference
Acknowledgements
This post was created with assistance from AI.