簡體   English   中英

如何檢查git branch是否有跟蹤分支?

[英]How do I check if git branch has a tracking branch?

我正在為bash編寫一個小git幫助器,我需要知道某個名稱的分支是否有跟蹤分支。

更具體地說,問題是如果你在一個沒有跟蹤分支的分支上運行git pull ,它將失敗,並帶有以下內容:

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=origin/<branch> foo

git pull --quiet也不會壓制此消息。

我設法找到了這個有用的快捷方式:

git rev-parse --symbolic --abbrev-ref foo@{u}

它完全符合我的需要,如果存在跟蹤分支,則輸出以下內容:

origin/foo

但是如果一個分支沒有跟蹤分支,那么這是輸出:

fatal: No upstream configured for branch 'foo'

這是相當不錯的,除了它存在非零狀態,並將其輸出到stderr。

所以我基本上想做的是:

tracking_branch=$(git do-some-magick foo)
if [[ -n $tracking_branch ]]; then
    git pull
fi

而不是這個:

tracking_branch=$(git rev-parse --symbolic --abbrev-ref foo@{u} 2> /dev/null)
if [[ -n $tracking_branch ]]; then
    git pull
fi

它實際上工作正常,但對我來說似乎不對。 有沒有其他方法可以做到這一點?

您可以嘗試這樣找到跟蹤分支:

git config --get branch.foo.merge

例子:

$ git config --get branch.master.merge
refs/heads/master

$ git config --get branch.foo.merge # <- nothing printed for non-tracked branch "foo"

根據git pull手冊,有關跟蹤分支的信息存儲在特定於存儲庫的.git/config

<repository>和<branch>的默認值是從git-branch [1] --track設置的當前分支的“remote”和“merge”配置中讀取的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM