Skip to content

Git branch from working directory

Henryk Paluch edited this page May 25, 2016 · 2 revisions

How to create git branch from working directory changes

Here is a typical situation from my project https://bitbucket.org/hpaluch/react-diag:

  • my current branch is master
  • I made lot of local changes to working directory (no add and no commit yet)
  • Suddenly I decided that to store these changes into new branch (called lunr_fulltext) without changing/commiting to master branch (finding that these changes seemed to be blind way)

Graphically it looks like this:

git log --graph --all --decorate --oneline
* 76936f0 (HEAD, origin/master, origin/HEAD, master) Setup on Ubuntu 14
* 92f2411 Now using browserify
* 7b86f75 Removed misleading comment
...

# lot of not yet added/commited files:
git add -n .
add 'Gruntfile.js'
add 'README.md'
add 'src/DiagTable.jsx'
add 'src/index.html'
add 'data-small/data.js'
add 'lib/lunr.min.js'

Here is solution - from http://stackoverflow.com/questions/1394797/move-existing-uncommited-work-to-a-new-branch-in-git

  • stash you working directory to temp area:
git stash
Saved working directory and index state WIP on master: 76936f0 Setup on Ubuntu 14
HEAD is now at 76936f0 Setup on Ubuntu 14
  • list your stashes:
git stash list
stash@{0}: WIP on master: 76936f0 Setup on Ubuntu 14
  • now create branch from stash:
 git stash branch lunr_fulltext 'stash@{0}'
Switched to a new branch 'lunr_fulltext'
On branch lunr_fulltext
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
# lot of warnings about diff uncommited files
  • verify that we our in new branch lunr_fulltext and commit changes there:
git branch
* lunr_fulltext
  master

git add .
git commit -m "Fulltext prototype with LUNR"
  • push branch lunr_fulltext to remote origin:
git push origin lunr_fulltext
  • switch back to master branch
git checkout master
Switched to branch 'master'
  • again look at graph:
git log --graph --all --decorate --oneline
* 431a68b (origin/lunr_fulltext, lunr_fulltext) Fulltext prototype with LUNR
* 76936f0 (HEAD, origin/master, origin/HEAD, master) Setup on Ubuntu 14
* 92f2411 Now using browserify

That's all:

  • our changes went to lunr_fulltext branch only.
  • Our working directory is copy of original master prior these changes...
  • add/commit will go again to master branch
Clone this wiki locally