Skip to content

Instantly share code, notes, and snippets.

@irace
Last active August 29, 2015 14:13
Show Gist options
  • Save irace/c20a8ae52c3bdb99692c to your computer and use it in GitHub Desktop.
Save irace/c20a8ae52c3bdb99692c to your computer and use it in GitHub Desktop.
Custom git commands that allow you to easily stash your work and switch branches, and then switch back and apply your stash: `pushb` and `popb`

Say you’re in the middle of working on something and need to switch branches in order to look at something else, but then want to go right back to what you were working on. This kind of flow reminds me of using pushd and popd so I made some very simple custom git commands to do this.

Usage

First, add the following files to your PATH (on OS X, just create them under /usr/local/bin and make them executable). Then use the commands like this:

bryan-MacBookPro-2a5158:project bryan$ git status
On branch some-new-feature
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   SomeNewFile.m

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    new file:   SomeInProgressFile.m

bryan-MacBookPro-2a5158:project bryan$ git pushb develop
Saved working directory and index state WIP on some-new-feature: 42d1093 Working on some new feature
HEAD is now at 42d1093 Thing I was working on previously
Switched to branch 'develop'

bryan-MacBookPro-2a5158:project bryan$ git status
On branch develop
nothing to commit, working directory clean

bryan-MacBookPro-2a5158:project bryan$ git popb
Switched to branch 'some-new-feature'
On branch some-new-feature
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   SomeNewFile.m

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    new file:   SomeInProgressFile.m

These scripts are really simple/naive and could certainly be made more robust, but I think this covers the basic use case pretty adequately.

#!/bin/bash
git stash; git checkout $1;
#!/bin/bash
git checkout @{-1}; git stash apply;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment