Home > Net >  Is there one command to create or checkout an existing branch?
Is there one command to create or checkout an existing branch?

Time:11-06

git switch <branch> allows me to move to an existing branch.

git switch -c <branch> allows me to create a new branch.

Is there a command where dependent on whether the branch already exists, it'll either create a new branch or check out the existing one?

CodePudding user response:

I'm not aware of such a command, but you can create an alias that will do it for you, in this example git csw (git show-branch will mark the current branch with * and will show that no branch has been reset):

$ git config alias.csw '!sh -c "git switch $1 || git switch -c $1"'
$ git show-branch
* [branch-a] b
 ! [master] h
--
*  [branch-a] b
*  [master] h
$ git csw master
Switched to branch 'master'
$ git show-branch
! [branch-a] b
 * [master] h
--
   [branch-a] b
 * [master] h
$ git csw branch-a
Switched to branch 'branch-a'
$ git show-branch
* [branch-a] b
 ! [master] h
--
*  [branch-a] b
*  [master] h
$ git csw branch-b
fatal: invalid reference: branch-b
Switched to a new branch 'branch-b'
$ git show-branch
! [branch-a] b
 * [branch-b] b
  ! [master] h
---
 *  [branch-a] b
 *  [master] h

CodePudding user response:

There is nothing built in, but it is easy to define an alias or write a script:

if git show-ref --quiet "refs/heads/$branchname"; then
  git switch "$branchname";
else
  git switch -c "$branchname";
fi

or perhaps

git show-ref --quiet "refs/heads/$branchname" || create=-c;
git switch ${create: "$create"} "$branchname"

Configuring it as alias:

git config --global alias.sw '!f() { if git show-ref --quiet "refs/heads/$1"; then git switch "$1"; else git switch -c "$1"; fi; }; f'

(or variant 2:)

git config --global alias.sw '!f() { git show-ref --quiet "refs/heads/$1" || create=-c; git switch ${create: "$create"} "$1"; }; f'

Then use:

git sw branch-to-checkout-or-create

CodePudding user response:

git checkout -B <branchname>
  •  Tags:  
  • git
  • Related