我正在为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
实际上它能正常工作,但是我感觉不太对劲。还有其他的方法可以实现这个吗?
rev-parse
会抛出错误。 - dentuzhik