是否有创建或签出现有分支的命令?

  • 本文关键字:分支 命令 创建 是否 git
  • 更新时间 :
  • 英文 :


git switch <branch>允许我移动到一个现有的分支

git switch -c <branch>允许我创建一个新的分支。

是否有一个命令依赖于分支是否已经存在,它将创建一个新的分支或检出现有的分支?

没有内置的东西,但是很容易定义别名或编写脚本:

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

或者

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

配置别名:

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'

(或变体2:)

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

然后使用:

git sw branch-to-checkout-or-create

我不知道这样的命令,但是你可以创建一个别名来为你做,在这个例子中,git csw (git show-branch将用*标记当前分支,并将显示没有分支被重置):

$ 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

最新更新