1637

I have two branches: master and dev

I want to create a "feature branch" from the dev branch.

Currently on the branch dev, I do:

git checkout -b myfeature dev

... (some work)

git commit -am "blablabla"
git push origin myfeature

But, after visualizing my branches, I got:

--**master**
------0-----0-----0-----0-----0
------------------------**dev**----**myfeature**

I mean that the branch seems fast-forward merged, and I don't understand why...

What am I doing wrong?

How can you branch off from another branch and push back to the remote repository for the feature branch?

All that in a branching model like the one described here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
revohsalf
  • 16,443
  • 3
  • 15
  • 4
  • To be clear, are you asking why the myfeature branch is ff merged, as opposed to some other form of merge? Or are you asking why it was merged at all? The latter question would make more sense to me, as I see no merge command preceding the apparent ff merge observation. – Andres Salas Apr 07 '22 at 22:39
  • 1
    in your case myfeature is just few commits ahead of dev, that's why it is visualized that way. They don't have and point where commits diverge. Once dev branch gets some additional commit, you'll see it as branches with diverged commits that can't be just fast-forwarded. – Sergey P. aka azure Jun 17 '22 at 08:48

12 Answers12

2259

If you like the method in the link you've posted, have a look at Git Flow.

It's a set of scripts he created for that workflow.

But to answer your question:

git checkout -b myFeature dev

Creates the MyFeature branch off dev. Do your work and then

git commit -am "Your message"

Now merge your changes to dev without a fast-forward

git checkout dev
git merge --no-ff myFeature

Now push the changes to the server

git push origin dev
git push origin myFeature

And you'll see it how you want it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abizern
  • 146,289
  • 39
  • 203
  • 257
  • 1
    Thanks for your answer ;) I did the same (without merging yet) After looking at Git Flow source code it's roughly the same... I don't get why when I create my feature branch, commit and push to it (remote), the branch seems merged when I visualize all my branches – revohsalf Dec 17 '10 at 13:36
  • Because you are pushing the myFeature branch to the server, and it shows that it has come off the dev branch. There are no merges. My example merges to the dev branch and pushes that merged branch to the server. – Abizern Dec 17 '10 at 13:49
  • 58
    what is the importance of pushing `myFeature` after it has been merged wit `dev`? – Alexander Suraphel Mar 21 '14 at 07:29
  • 3
    @spartacus If `myFeature` branch was pushed to the server before merging, then nothing. But if `myFeature` isn't yet pushed to the server and you want it to appear in the server, you must push it appart. – xOneca Mar 22 '14 at 18:29
  • 37
    is `git checkout -b myFeature dev` the same as these 3 commands: `git checkout dev`, then `git branch myFeature`, and then `git checkout myFeature`? – Kevin Meredith Apr 09 '14 at 16:56
  • 4
    It is, or it should be. Are you seeing something different? – Abizern Apr 09 '14 at 23:33
  • The way I read your sequence is: **1)** branch off, do your work and commit **2)** switch back to dev and merge it with feature **3)** push dev **4)** push feature **My question:** Why do push *both* `dev` & `feature`? shouldn't you just push after step 3 and be done? Don't you have all the new feature code you needed merged? – mfaani Aug 16 '16 at 22:02
  • How would you do this with an already existing 'feature' branch? Like in the OP's question? – Pitt Sep 16 '16 at 19:08
  • @Honey once you have checked out dev and merged the feature branch into it, just pushing dev would be enough - I agree – Pitt Sep 16 '16 at 19:14
  • What if i want to push myFeature on the remote server before i finish work on this feature? May i skip merge with dev? (Feature do not exists on remote server yet) – Den Kison Jan 26 '17 at 09:15
  • Is there a way to define `dev` as the default branch from where I want to create the others from, removing the need of the last param in `git checkout -b newBranch dev`, making it `git checkout -b newBranch`? – ErickXavier Jun 15 '18 at 18:10
  • 79
    To clarify for other newbies, [this is what a `--no-ff` merge looks like](https://i.stack.imgur.com/FMD5h.png) – A__ Oct 06 '18 at 23:01
  • This only works for me if I branch off of `origin/dev`, not off of `dev`. – temporary_user_name Sep 05 '19 at 16:41
  • 1
    I am glad I found @A__'s comment, this helped a lot to visualize why to use the no fast-forward, I feel like this should be added to the answer! If you use the merge with fast-forward there is no clear way to tell where your feature starts and ends as it brings all the commits from the new feature branch into the development branch with no reference points! – AJ Smith 'Smugger' Jan 02 '20 at 20:39
  • whats the diffrence between git checkout -b myFeature dev & git checkout -b myFeature origin/dev. What to do if local dev branch is not updated? – Shrikant Phadke Sep 17 '20 at 10:33
  • 1
    why `git commit -am` instead of `git commit -m` ? – Cin88 May 24 '21 at 21:44
  • @Cin88 https://explainshell.com/explain?cmd=git+commit+-am – AndW Jul 20 '23 at 22:28
679

If you want create a new branch from any of the existing branches in Git, just follow the options.

First change/checkout into the branch from where you want to create a new branch. For example, if you have the following branches like:

  • master
  • dev
  • branch1

So if you want to create a new branch called "subbranch_of_b1" under the branch named "branch1" follow the steps:

  1. Checkout or change into "branch1"

     git checkout branch1
    
  2. Now create your new branch called "subbranch_of_b1" under the "branch1" using the following command.

     git checkout -b subbranch_of_b1 branch1
    

    The above will create a new branch called subbranch_of_b1 under the branch branch1 (note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though).

  3. Now after working with the subbranch_of_b1 you can commit and push or merge it locally or remotely.

A sample Graphical Illustration Of Creating Branches Under another Branch

Push the subbranch_of_b1 to remote:

 git push origin subbranch_of_b1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Praveen George
  • 9,237
  • 4
  • 26
  • 53
  • 11
    how to push the subbranch_of_b1 to remote ?? – user269867 Dec 07 '16 at 21:03
  • 18
    @user269867 : " git push origin subbranch_of_b1 " will do this job for you. – Praveen George Dec 08 '16 at 04:56
  • 4
    Now , If i push changes to master , will it occur in branch1 automatically ? – Master Yoda Nov 28 '17 at 07:25
  • 2
    *note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though* that's what I was looking for – felipsmartins Mar 05 '18 at 13:27
  • 43
    I came here wondering if `git checkout -b some-branch` is shorthand for `git checkout -b some-branch master`. It turns out that `git checkout -b some-branch` is shorthand for `git checkout -b some-branch ` – Frank Henard May 25 '18 at 16:16
  • `git push origin subbranch_of_b1` is exactly what OP said they already did. This answer is incomplete as it doesn't address how to push without ff merging. – A__ Oct 06 '18 at 22:57
  • 2
    @Frank. The default of "" has gotten me into trouble sometimes, thus my personal preference is to spell-out the source branch ! Aka, my assumptions on my part were bad sometimes. – granadaCoder Jun 19 '19 at 13:03
  • thanks. only it is a little confusing to call the new branch `subbranch_of_b1`, it is just a new branch created from base branch, `branch1` in this case. It is in equal level as other branches in the repo. There isn't a thing as sub-branch in git, just not the logic. – seedme Nov 23 '21 at 02:19
83

Various ways to create a branch in Git from another branch:

This answer adds some additional insight, not already present in the existing answers, regarding just the title of the question itself (Create a branch in Git from another branch), but does not address the more narrow specifics of the question which already have sufficient answers here.

I'm adding this because I really needed to know how to do #1 below just now (create a new branch from a branch I do not have checked out), and it wasn't obvious how to do it, and Google searches led to here as a top search result. So, I'll share my findings here. This isn't touched upon well, if at all, by any other answer here.

While I'm at it, I'll also add my other most-common git branch commands I use in my regular workflow, below.

1. To create a new branch from a branch you do not have checked out:

Create branch2 from branch1 while you have any branch whatsoever checked out (ex: let's say you have master checked out):

git branch branch2 branch1

The general format is:

git branch <new_branch> [from_branch]

man git branch shows it as follows. What I call <new_branch> is what they call <branchname>, and what I call [from_branch] is what they call [<start-point>]:

git branch [--track | --no-track] [-l] [-f] <branchname> [<start-point>]

2. To create a new branch from the branch you do have checked out:

git branch new_branch

This is great for making backups before rebasing, squashing, hard resetting, etc.—before doing anything which could mess up your branch badly.

Example: I'm on feature_branch1, and I'm about to squash 20 commits into 1 using git rebase -i master. In case I ever want to "undo" this, let's back up this branch first! I do this ALL...THE...TIME and find it super helpful and comforting to know I can always easily go back to this backup branch and re-branch off of it to try again in case I mess up feature_branch1 in the process:

git branch feature_branch1_BAK_20200814-1320hrs_about_to_squash

The 20200814-1320hrs part is the date and time in format YYYYMMDD-HHMMhrs, so that would be 13:20 hours (1:20 pm) on 14 Aug. 2020. This way I have an easy way to find my backup branches until I'm sure I'm ready to delete them. If you don't do this and you mess up badly, you have to use git reflog to go find your branch prior to messing it up, which is much harder, more stressful, and more error-prone.

Interjection: notes about git checkout vs git switch

  1. The classic, universal "Swiss army knife" which can do 1000 things: git checkout.
  2. The new and experimental alternative commands to git checkout: git switch + git restore.

git switch was added recently in Git v2.23. See your git version with git --version. It is designed to be an extremely limited form of git checkout, designed only to switch branches rather than also having the ability to check out or restore files, like git checkout can do. Read more here: https://www.git-tower.com/learn/git/commands/git-switch.

See also: What does git checkout still do after git switch got introduced?. git restore offers some of the rest of the functionality of git checkout which git switch does not contain.

Both man git switch and man git restore caution:

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

So, feel free to stick with git checkout if you like. Its behavior is not likely to change.

I pretty much just use git checkout myself, but you are welcome to use git switch (and git restore to restore or "check out" files) if you like.

3. To create and check out a new branch from the branch you do have checked out:

# the standard, "classic" command most people still use; `-b` stands
# for "create 'b'ranch"
git checkout -b new_branch

# the newer, "experimental" command now available as of Git v2.23; `-c` stands
# for "'c'reate branch"
git switch -c new_branch

To make it obvious what is happening there, know that this one command above is equivalent to these two separate commands:

# classic
git branch new_branch
git checkout new_branch

# OR: new/experimental as of Git v2.23
git branch new_branch
git switch new_branch

4. To create and check out a new branch from a branch you do not have checked out:

# classic
git checkout -b new_branch from_branch

# OR: new/experimental as of Git v2.23
git switch -c new_branch from_branch

To make it obvious what is happening there, know that this one command above is equivalent to these three separate commands:

# classic
git checkout from_branch
git branch new_branch
git checkout new_branch

# OR: new/experimental as of Git v2.23
git switch from_branch
git branch new_branch
git switch new_branch

5. To rename a branch

Just like renaming a regular file or folder in the terminal, git considered "renaming" to be more like a 'm'ove command, so you use git branch -m to rename a branch. Here's the general format:

git branch -m <old_name> <new_name>

man git branch shows it like this:

git branch (-m | -M) [<oldbranch>] <newbranch>

Example: let's rename branch_1 to branch_1.5:

git branch -m branch_1 branch_1.5

OR, if you already have branch_1 checked out, you can rename the currently-checked-out branch to branch_1.5 like this:

git branch -m branch_1.5

6. To create a new feature branch (feature2) based off of the latest upstream changes on main when you currently have feature1 checked out

Let's put a lot of what we learned above together to present a very common example we need to run whenever we finish one feature and need to start another one.

# The beginner/intermediate way

git checkout main           # check out main branch
git pull                    # pull latest upstream changes down
git checkout -b feature2    # create branch `feature2` from `main`, and check
                                # it out, all in one step`

# The advanced way

# [this is what I do--I'll explain why, below]
git fetch origin main:main      # pull latest upstream changes down from the
                                    # remote `main` branch, to the
                                    # locally-stored remote-tracking **hidden**
                                    # branch named `origin/main`, **and** to
                                    # the local `main` branch
git checkout -b feature2 main   # create branch `feature2` from `main`, and
                                    # check it out, all in one step`

# OR (nearly the same thing)
git fetch origin main           # pull latest upstream changes down from the
                                    # remote `main` branch, to the
                                    # locally-stored remote-tracking **hidden**
                                    # branch named `origin/main`. This does NOT
                                    # update the local `main` branch though!
git checkout -b feature2 origin/main # create branch `feature2` from
                                        # `origin/main`, and check it out, all
                                        # in one step`

So, when I'm on branch feature1, and have just finished it and am ready to start on a new feature2 based off of the latest main branch, why do I do this:

git fetch origin main:main
git checkout -b feature2 main

...instead of this?:

git checkout main
git pull
git checkout -b feature2

The answer, surprisingly, is that git checkout can be a horribly slow and heavy operation!—taking up to 3+ hours on a massive mono-repo utilizing git lfs post-checkout hooks in the repo's .git/hooks/post-checkout file. Let me explain. The .git/hooks/post-checkout file is an executable file containing a script that git will run after each time you run git checkout. If it contains a call to git lfs post-checkout "$@", then it may try to download 20+ GB of git lfs data (specific to the repo I work in—your scenario may vary) after running an innocent-looking git checkout. I don't want to do that! So, I skip the git checkout process to avoid that hassle and get started on my feature2 branch immediately without downloading all of that stuff I don't need first!

See also:

  1. Quick links to my answers I reference frequently and consider to be "git fundamentals":
    1. Various ways to create a branch in git from another branch
    2. All about checking out files or directories in git
    3. Who is "us" and who is "them" according to Git?
    4. How to use git diff filters via --diff-filter=
    5. How to use git lfs as a basic user: What is the difference between git lfs fetch, git lfs fetch --all, and git lfs pull?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
  • 2
    Best answer. Other answers are confusing since they tend to focus on branching and switching to the created branch at the same time using `git checkout`. – Danijel Mar 04 '21 at 09:29
75

Create a Branch

  • Create branch when master branch is checked out. Here commits in master will be synced to the branch you created.

    git branch branch1

  • Create branch when branch1 is checked out . Here commits in branch1 will be synced to branch2 git branch branch2


Checkout a Branch

git checkout command switch branches or restore working tree files

  • git checkout branchname

Renaming a Branch

  • git branch -m branch1 newbranchname

Delete a Branch

  • git branch -d branch-to-delete
  • git branch -D branch-to-delete ( force deletion without checking the merged status )

Create and Switch Branch

  • git checkout -b branchname

Branches that are completely included

  • git branch --merged


Branch Differences [ git diff branch1..branch2 ]

Multiline difference

  • git diff master..branch1

Singleline difference

  • git diff --color-words branch1..branch2
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gnanasekar S
  • 1,820
  • 14
  • 15
  • 3
    Also after renaming the branch use `git push origin :old-name new-name` to delete the old-name remote branch and push the new-name local branch. – 95faf8e76605e973 Aug 09 '19 at 06:36
37

To create a branch from another branch in your local directory you can use the following command.

git checkout -b <sub-branch> branch

For example:

  • the name of the new branch to be created is 'XYZ'
  • the name of the branch, 'ABC', under which 'XYZ' has to be created
git checkout -b XYZ ABC
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sumit Ghewade
  • 473
  • 4
  • 16
19

Git 2.23 introduces git switch and git restore to split the responsibilities of git checkout.

Creating a new branch from an existing branch as of Git 2.23:

git switch -c my-new-branch

Switched to a new branch 'my-new-branch'

  • -c is short for --create and replaces the well-known git checkout -b

Take a look at this GitHub blog post explaining the changes in greater detail:

Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JSON C11
  • 11,272
  • 7
  • 78
  • 65
13

Do simultaneous work on the dev branch. In your scenario, the feature branch moves forward from the tip of the dev branch, but the dev branch does not change. It's easier to draw as a straight line, because it can be thought of as forward motion. You made it to point A on dev, and from there you simply continued on a parallel path. The two branches have not really diverged.

Now, if you make a commit on dev, before merging, you will again begin at the same commit, A, but now features will go to C and dev to B. This will show the split you are trying to visualize, as the branches have now diverged.

*-----*Dev-------*Feature

Versus

       /----*DevB
*-----*DevA
       \----*FeatureC
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marshall Davis
  • 3,337
  • 5
  • 39
  • 47
12

If you want to make a branch from some another branch then follow the below steps:

Assumptions:

  1. You are currently in the master branch.
  2. You have no changes to commit. (If you have any changes to commit, stash it!)
  3. BranchExisting is the name of branch from which you need to make a new branch with name BranchMyNew.

Steps:

  1. Fetch the branch to your local machine.

    git fetch origin BranchExisting : BranchExisting
    

This command will create a new branch in your local with same branch name.

  1. Now, from the master branch checkout to the newly fetched branch

    git checkout BranchExisting
    
  2. You are now in BranchExisting. Now create a new branch from this existing branch.

    git checkout -b BranchMyNew
    

Here you go!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Darshit
  • 141
  • 1
  • 8
3

this is going to create new branch from current branch.

git checkout -b your_new_branch_name 

if you want to create new_branch of an existing branch then

git checkout -b your_new_branch_name existing _branch_name
1

For creating a branch from another one can use this syntax as well:

git push origin refs/heads/<sourceBranch>:refs/heads/<targetBranch>

It is a little shorter than "git checkout -b " + "git push origin "

Alexander Samoylov
  • 2,358
  • 2
  • 25
  • 28
1

Switch to the develop branch:

git checkout develop

Creates feature/foo branch of develop.

git checkout -b feature/foo develop

Merge the changes to develop without a fast-forward

git checkout develop
git merge --no-ff myFeature

Now push changes to the server:

git push origin develop
git push origin feature/foo
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Navnav221
  • 43
  • 1
  • 4
  • 5
    not sure why this comment is needed when it's pretty word-to-word with the accepted answer and has less context in the comments too. – Yashank Jan 26 '21 at 09:01
  • This was more helpful for me than original answer. I have been regular user of git in past but since last 2 year, i was using some other source control. i just wanted to have quick refresher instead of going through large answer – Anjani Aug 12 '22 at 11:41
  • [The accepted answer](https://stackoverflow.com/questions/4470523/create-a-branch-in-git-from-another-branch/4470822#4470822). – Peter Mortensen Nov 09 '22 at 20:56
1

It's worked for me:

Go to your GitHub repository, and select the branch name from where you want to create a new branch, as shown in the below image:

Image 2

Then type the branch name you want to create, and click on Create branch.

Image 2

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131