0

I want to create a new branch and check it out. However, if the branch name I'm creating already exists, I don't want to get an error, I simply want git to update the already existing branch to the point I'm checking it out at.

Here is what I'm doing:

$ git branch
  develop
* foobar
$ git checkout -b develop origin/develop
fatal: A branch named 'develop' already exists.
$ git update-ref refs/heads/develop origin/develop
$ git checkout develop
Switched to branch 'develop'
$ git branch
* develop
  foobar
$

Here is something like what I want:

$ git checkout --update-if-exists -b develop origin/develop
Switched to branch 'develop'
$ git branch
* develop
  foobar
$
Alexander Bird
  • 38,679
  • 42
  • 124
  • 159

1 Answers1

-1

I don't know of a single git command that lets you do this, but here's a bash script that (I think) does what you want:

#!/bin/bash
git fetch origin "$1"
if [[ 0 != $? ]]; then
  git branch "$1"
fi
git checkout "$1"

Edit: (after commentary)

I see. Surely we can fix the script though like this:

#!/bin/bash
git branch "$1"
if [[ 0 != $? ]]; then
  git update-ref "refs/heads/$1" "origin/$1"
fi
git checkout "$1"

And, if you don't want it to display errors when the first command fails, you could silence those errors like this:

#!/bin/bash
git branch "$1" 2>/dev/null
if [[ 0 != $? ]]; then
  git update-ref "refs/heads/$1" "origin/$1"
fi
git checkout "$1"
Chris Beck
  • 15,614
  • 4
  • 51
  • 87
  • I don't think that will work. That checks if the branch exists _in origin_. I want to know if the branch exists _locally_. And after that, I don't want to simply checkout the branch locally, I want to update it to point to the commit that origin has it at. – Alexander Bird Sep 16 '15 at 16:22