Git – switching between branches in the middle of work

For various reasons (code review mostly) I need to switch from current development branch to other branches quite often.

Currently, I use either ‘git stash‘ to shelve the uncommitted changes, checkout other branch, then switch back and do ‘git stash apply’

However, sometimes I’d have some newly added files there, which are not tracked. Unfortunately, stashing does not affect them. In this case I’d have to add them to the index and stash.

What I am looking here for is a workflow where I’d have to perform a minimal set of actions to switch the branches, preferably avoiding adding of files into the index.

  • Branch only 1 or 2 files in git for android project
  • How do you store node_modules in git?
  • Removing old commits from github project
  • Mercurial error: abort no username supplied
  • How to push to a remote branch without providing the full push refspec?
  • How do you commit all files with one or more exception in git?
  • Bumping version numbers for new releases in associated files (documentation)
  • 2-Version software: Best VCS approach?
  • 3 Solutions collect form web for “Git – switching between branches in the middle of work”

    you can clone the repo to another directory and default to the branch you want:

    # assume your original repo is in myproj
    $ git clone myproj myproj_clone --branch my_branch

    If you then go to the myproj_clone folder, it’ll be in your branch

    $ cd myproj_clone
    $ git branch
    * my_branch

    You could clone the repository and review/work on the clone. Delete the clone when you are done. If you do happen to make changes on the branch/clone, you can push them back. I think a local clone is cheap. And even if it was not, disk space is still cheaper than your time.

    I’m not sure that cloning is the right solution, but since 2 answers are proposing that it’s on the brain, so I’m offering a modification on that theme. cloning may not be cheap. In terms of disk-space, it’s irrelevant, but the clone itself make take several seconds and that’s too much time to waste on an unnecessary operation. As an alternative, you can simply create a new working directory using the old git working dir. ie, if your current working dir is “a” (with changes and un-staged files), try:

    $ mkdir ../b
    $ cd ../b
    $ echo 'gitdir: ../a/.git' > .git
    $ git checkout -f foo

    Now b is effectively a clone of a, on branch foo, and you’ve got two working directories to play with. Do what you need to on branch foo in working dir b, then go back to a and checkout the branch you were on when you left.

    Git Baby is a git and github fan, let's start git clone.