DEV Community

Chetan Pratap Singh
Chetan Pratap Singh

Posted on

After cloning code from master branch to local directory. How to switch to your branch(with code from master branch).

So, I'm cloning code from master branch to my local directory. And when i open the code in (INTELLIJ Idea) on lower right side its shows master branch but instead of master branch i want my own branch(Branch i made from master branch) so that i can do changes on code and commit it and the commits only goes to my branch not master branch.

Oldest comments (5)

Collapse
 
janlimpens profile image
Jan

First, check out master:
git checkout master
get the newest version of it
git pull (assuming you did not change master in another session)
Then, create a new feature branch
git branch my_feature_branch
switch to it
git checkout my_feature_branch
Now, work and commit as often as you like
git commit -a (or a variation of it)
When you want to put your changes into master, you need to merge. To do so:
git checkout master
git pull
Now, your master is updated.
git merge my_feature_branch
mixes your changes into master. It will generate a merge commit.
To publish your changes, do:
git push

Your my_feature_branch has not been published to your origin repository. It just exists locally. It's changes, however, have all found their way into master. Probably you do not need it anymore, because you can allways create a new branch from master. If you want to put it into origin, out of some reason, you need to check it out and push it. As it does not yet exist in origin, you will need to execute a command that git will show you.

Collapse
 
chetanpratap profile image
Chetan Pratap Singh

Is there any way to do it without creating a new branch and keeping old branch. Commit changes to old branch

Collapse
 
janlimpens profile image
Jan

Of course, you can always switch to another branch and commit there.

git checkout old_branch && git pull
git commit -a
git checkout master && git pull
git merge old_branch
now, you might have to resolve some conflicts,
git add file_with_conflict.pl
git commit
git push

The advantage of keeping your distance from master short, is that the code does not diverge as much between branches and there will be less conflicts.

Therefore, if you want to keep using a specific branch (because others use it as well) and want to keep it close to master, you

git checkout master && git pull
git checkout old_branch && git pull
now both are at their latest revision and you are on old_branch. To get old_branch closer to master you do
git merge master, fix eventual conflicts as above and
git push
Now, old_branch has everything from master, plus the stuff, you have not yet merged into master.

Thread Thread
 
chetanpratap profile image
Chetan Pratap Singh

Thank you, you’re amazing!

Thread Thread
 
janlimpens profile image
Jan

No problem, git can be intmidating at first, but you'll get the hang of it. We've all been there.