Home > Mobile >  Git Stash Apply on Master insted of Local branch
Git Stash Apply on Master insted of Local branch

Time:11-03

I was on my local branch with current file changes and had to do a pull on Master. So I did-

git stash git checkout master git pull origin master

At this step usually I do git checkout myCurrentBranch, and then git stash apply stash@{0}, but due to oversight I did the apply stash on the Master branch itself.

How can I undo this step? And get back my file changes on myCurrentBranch?

CodePudding user response:

You should be able to just do the following:

git stash
git checkout myCurrentBranch
git stash apply stash@{0}

This will return your changes to the stash and return the master branch to a clean state before switching back to your local branch and reapplying the stash there instead.

CodePudding user response:

Since you used git stash apply rather than git stash pop, you still have your saved stash. This means that you can wipe out the current changes with:

git reset --hard

followed by git checkout (or git switch) to your desired branch and another git stash apply.

Related, but nothing to do with git stash

You can save yourself a lot of effort in the future by avoiding git pull. You do not need to update your master at this point, and in fact, you may be able to just delete your master branch entirely. Instead of:

git stash
git checkout master
git pull
git checkout original-branch
git stash apply
# inspect and make sure all is well, and last:
git stash drop

you can use:

git fetch origin
# or just git fetch - "origin" is the usual default

When the fetch has finished, your origin/master is updated. Instead of using your own master, you can now use your origin/master. Note that origin/master is not a branch name: it's a remote-tracking name instead. It remembers what your Git saw on the other Git over at origin, in their master, the last time you ran git fetch origin or git fetch. Running git fetch origin updates your origin/master automatically, because it's your Git's memory of their branch: if they've updated their branch, your system updates and remembers this. If they have not updated their branch, your system does not have to update anything, and doesn't.

Since you never need to navigate away from your current branch, you never have to use git stash either.

(If you want to inspect what came in, i.e., see what their master—your origin/master—looks like, there are various ways to do that, too, without disrupting your existing branch, but let's stop here since that wasn't your question.)

  • Related