Is there a cleaner way to handle “git stash apply”?

I'm having problems with recovering changes from a stashed and untracked file in git. See minimal example below:

mkdir test_stash
cd test_stash/
git init
echo "text" | tee a.txt b.txt
git add a.txt
git commit -m "First commit"
git stash -u #stash b.txt
echo "newtext" > b.txt
git add b.txt
git commit -m "Second commit"
git stash apply

This returns me an error:

b.txt already exists, no checkout
Could not restore untracked files from stash entry

The example alone is a bit silly, but I ran into this problem when stashing changes before pulling from remote and then finding out that a new file had been created on remote with the same name.

After some googling I was able to recover the changes with:

git checkout stash -- .
git checkout stash^3 -- .
git reset HEAD . #to unstage

but this seems quite hacky. Isn't there a way to force my git stash apply, thus bringing my workspace to the original state before the stash? The changes on b.txt are already committed anyway, so it's not like I would risk losing unsaved changes.

1 Answer

When you save a stash git also remembers the commit. So you can simply create a new branch based on this commit with git stash branch <branchname> instead of applying the stash.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like