git stash – to switch between uncommitted versions

Issue

[git newbie]
Say I’m working on a new file and I write a story:

Version1: A guy walks into a bar
          [here I tell my story]

At this point I like what I wrote but I wish to make some changes, so I stash my changes:

$git stash save -u 'version1: a guy walks'

message:

Saved working directory and index state On dev_story: version1: a guy walks

now I change it:

Version2: A nice dude walks into a bar
          [here I tell a slighly different story]

and stash it again:

$git stash save -u 'version2: a dude walks'

message:

Saved working directory and index state On dev_story: version2: a dude  walks

checking my stash list I see:

$ git stash list
[email protected]{0}: On dev_story: version2: a dude walks
[email protected]{1}: On dev_story: version1: a guy walks

I wish to show my work to a friend and debate version1 vs version2.

when I try to apply [email protected]{0} it doesn’t show ‘a guy walks…’
what I have tried:

$ git stash show [email protected]{0}  //new line no error

$ git stash apply [email protected]{0} 

test/story.txt already exists, no checkout
error: could not restore untracked files from stash

Solution

$ git stash show [email protected]{0} //new line no error

Git showed you nothing here because your file was untracked. git stash show will not show you untracked files unless you ask with -u.

$ git stash show -u [email protected]{0}
test/story.txt | 1 +
1 file changed, 1 insertion(+)

$ git stash show -u -p [email protected]{0}
diff --git a/test/story.txt b/test/story.txt
new file mode 100644
index 0000000..f5d91d3
--- /dev/null
+++ b/test/story.txt
@@ -0,0 +1 @@
+A nice dude walks into a bar

$ git stash apply [email protected]{0} 

test/story.txt already exists, no checkout
error: could not restore untracked files from stash

You already had a test/story.txt file with changes. Because your stashed change creates a new file, git is protecting you from it overwriting the existing test/story.txt.


See Stashing and Cleaning for more about the stash.

In general, I find it quite easy for the stash to get messy and to forget what’s in there or what it applies to. Its useful to stash away changes for just a moment. For anything longer, I would recommend using commits and branches.

If you need to save some unfinished work, make a commit and log it as a "wip" (work in progress). Then amend the commit later (see Changing the Last Commit. If you want to have two different versions, make a branch; that’s what they’re good at. Branches are very cheap.

Answered By – Schwern

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published