Skip to content

Instantly share code, notes, and snippets.

@brookinc
Last active November 23, 2021 09:34
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brookinc/e2589a8c5ca33f804e4868f6bfc18282 to your computer and use it in GitHub Desktop.
Save brookinc/e2589a8c5ca33f804e4868f6bfc18282 to your computer and use it in GitHub Desktop.
A script to `git stash` only the currently staged changes.
#!/usr/bin/env bash
# This script stashes the currently staged changes, and leaves everything else in the working directory as-is.
# (source: https://stackoverflow.com/questions/14759748/stashing-only-staged-changes-in-git-is-it-possible/39644782#39644782)
# Prompt for the desired repo path
REPOPATH=
read -p "Enter the repo path, or press ENTER for current dir: " REPOPATH
# Read the desired stash description from the command line, or prompt the user for it if necessary
STASHNAME=$1
while [ "$STASHNAME" = "" ] ; do
read -p "Enter a description for this stash: " STASHNAME
done
#git -C "$REPOPATH" log -1
# Stash everything temporarily. Keep staged files, discard everything else after stashing.
#git --git-dir $REPOPATH/.git stash --keep-index
git -C "$REPOPATH" stash --keep-index
# Stash everything that remains (only the staged files should remain). This is the stash we want to keep, so give it a name.
git -C "$REPOPATH" stash save "$STASHNAME"
# Apply the original stash to get us back to where we started
git -C "$REPOPATH" stash apply stash@{1}
# Create a temporary patch to reverse the originally staged changes and apply it
git -C "$REPOPATH" stash show -p | git -C "$REPOPATH" apply -R
# Delete the temporary stash
git -C "$REPOPATH" stash drop stash@{1}
@Gerst20051
Copy link

Thanks @typebrook that works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment