Search code examples
gitversion-controlbranchgit-stashgit-add

Git stash partially staged file


Is there a way to stash partially staged files (created with git add -p) in a straightforward easy manner? I already know about git stash -p which behaves like add but with stashing, but I already staged the stuff I'd like to save for later.

Maybe there is also a better way of doing what I want. I just want to save a change I made that does not belong to this branch, which I want to apply later in another branch. The changes are not committed yet.


Solution

  • [edit] actually, the easiest way is probably :

    git commit
    

    One rather simple way, using usual stash commands, would be :

    git stash -k     # stash your changes but keep the index
    git stash        # stash again (only you index)
    git stash pop --index stash@{1}  # restore your repo to how it was
    

    Your top stash will now have your index (and only your index).


    Actually, creating a stash (a regular stash) already stores your index in a separate place.

    To view this : run git stash, then git log --graph --oneline stash :

    $ git stash
    $ git log --oneline --graph stash
    *   f94915d (refs/stash) WIP on master: 963f4f4 Merge branch 'fork'
    |\  
    | * f45cef3 index on master: 963f4f4 Merge branch 'fork'
    |/  
    *   963f4f4 (HEAD -> master) Merge branch 'fork'
    ...
    

    The commit named "index on ..." contains the content of the index you had when running git stash.

    You can use that commit as a regular commit ; as you can see, it is the second parent of the actual stash (stash^2, or f94915d^2 in my example).


    git stash has other subcommands, intended for scripting usage.

    For example : git stash create will create the commits to be stored in a stash, but simply won't update the reference named stash nor its reflog :

    $ git stash create
    8bdb3b5accb08a8e16ec88a49682fcbf10d29ccf   # <- you want to do something with this commit
    

    The content of your index would be {thathash}^2. So another way is :

    # will create a banch 'myindex' containing your current index :
    $ git branch myindex $(git stash create)^2