6

Ok so I meant to be working on a branch called directory-layout, but it turns out that I am working on a branch called master. This is a problem.

I have not yet performed git add . nor git commit -m "I've made a horrendus mistake I'm sorry"

What do I do to add my changes to another (or new) branch and why?

Rob Truxal
  • 5,856
  • 4
  • 22
  • 39
  • 1
    First, if you mean to create that as a new branch starting from the current commit, just use `git checkout -b directory-layout` and you're all good. If not: well, I know this might *seem* dangerous, but it's quite safe: whether `directory-layout` is an existing branch, or is to be made from an existing remote-tracking branch, *try* just running `git checkout directory-layout`. If that works, you're good to go. If not, use one of the backup strategies. See https://stackoverflow.com/q/22053757/1256452 – torek Jul 19 '17 at 05:16

2 Answers2

5

If that branch is a new one, you can simply create it:

git checkout -b anewbranch
git add .
git commit -m "message"

But if that branch is an old one, you can cherry-pick the commit instead:

  • add, and commit
  • switch to the old branch
  • git cherry-pick master

Then reset master to its previous commit

git checkout master
git reset --hard @~1

Another approach would be to use git stash, then switch to the old branch and stash apply.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    The point is: I prefer committing first: that way I don't lose anything. Then I can switch that commit around. – VonC Jul 19 '17 at 04:44
  • 1
    Interesting. So `cherry-pick` lets me transfer the `HEAD` of one branch to another? – Rob Truxal Jul 19 '17 at 04:51
  • 2
    @RobTruxal cherry-pick let you apply any commit (or set of commits) to another branch. https://git-scm.com/docs/git-cherry-pick – VonC Jul 19 '17 at 04:52
2

Here is what I would try doing.

  git checkout -b <newbranch> 
Boshika Tara
  • 234
  • 2
  • 4