Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create git branch without changing working copy

Tags:

git

I just created a new repository and added a remote:

git init
git remote add foo something

Now I want git to be on the most recent commit of foo/master. Usually, that would just be:

git checkout master

Git is clever enough to use foo/master these days.

The challenge is that I already have files in my working copy and I don't want them to change. I want git diff to show me changes and I want to commit the local state and push it to foo.

Background: The local state is a generated website about to be pushed to Github Pages.

like image 357
qznc Avatar asked Jan 11 '17 16:01

qznc


People also ask

How do I create a branch without losing changes?

3. Using the git checkout Command. The git checkout -b <BranchName> command will create a new branch and switch to it. Moreover, this command will leave the current branch as it is and bring all uncommitted changes to the new branch.

Can I create a new branch with current changes?

You can do a checkout and create a new branch with all local and current changes transferred over.

How do I make a branch identical?

To make a merge, you check out some branch ( A in these cases) and then run git merge and give it at least one argument, typically another branch name like B . The merge command starts by turning the name into a commit ID. A branch name turns into the ID of the tip-most commit on the branch.


1 Answers

If you have just done git init in a new repository (as opposed to re-init-ing an existing repository), and have not yet run git commit, you are currently on an unborn branch (normally master-as-unborn-branch). What this means is that HEAD contains the name master, while the branch named master does not actually exist.

If you have furthermore not run any git add commands, your index is currently empty.

The state that you would like to have is to have the name master point to the same commit as foo/master, without changing the contents of the work-tree. But first you need to obtain all the commits from remote foo:

$ git fetch foo

Now you can create the branch itself:

$ git branch master foo/master

Since you're already on master—it was merely "unborn"—you are now still on master and master points to the same commit as foo/master.

Your index is still empty, so git status will show you as having deleted every file from the HEAD commit, with every file in the work-tree as an untracked file. If you would like to populate your index from the current commit, you can now do:

$ git read-tree HEAD

and then git reset various files to restore them. If not—if you just want to use the work-tree—you can simply git add . (though you may want to set up a .gitignore first).

like image 97
torek Avatar answered Oct 30 '22 14:10

torek