问题描述
我是新来的shell脚本并不能想出解决办法。如果你不熟悉,命令的Git分支返回类似
I am new to shell scripting and can't figure this out. If you are unfamiliar, the command git branch returns something like
* develop
master
,其中星号标记当前已签出的分支。当我运行在终端如下:
, where the asterisk marks the currently checked out branch. When I run the following in the terminal:
git branch | grep "*"
我得到:
* develop
如预期。
然而,当我运行
test=$(git branch | grep "*")
或
test=`git branch | grep "*"`
然后
echo $test
,结果仅仅是一个目录中的文件的列表。我们如何做测试的值=*发展?
, the result is just a list of files in the directory. How do we make the value of test="* develop"?
那么下一步(一旦我们得到*发展到一个变量名为test),是让子。请问这只是下面?
Then the next step (once we get "* develop" into a variable called test), is to get the substring. Would that just be the following?
currentBranch=${test:2}
我与子功能的玩弄和我坏替代的错误很多,不知道为什么。
I was playing around with that substring function and I got "bad substitution" errors a lot and don't know why.
推荐答案
*为扩展,你可以做的是利用战略经济对话,而不是grep和立即得到分支的名称:
The * is expanded, what you can do is use sed instead of grep and get the name of the branch immediately:
branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
和一个版本用git象征-REF,由Noufal易卜拉欣建议
And a version using git symbolic-ref, as suggested by Noufal Ibrahim
branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
要阐述的扩大,(马可已经没有,)扩张发生在回音,当你做回声$测试
包含$测试*大师然后*是根据正常扩张规则扩大。共进晚餐preSS这个一会要引用变量,如由Marco:回声$测试
。另外,如果你摆脱了星号的你回声之前,一切都会好起来的,例如回声$ {测试:2}
只是回声大师。另外,您可以为您已经提出重新分配给它:
To elaborate on the expansion, (as marco already did,) the expansion happens in the echo, when you do echo $test
with $test containing "* master" then the * is expanded according to the normal expansion rules. To suppress this one would have to quote the variable, as shown by marco: echo "$test"
. Alternatively, if you get rid of the asterisk before you echo it, all will be fine, e.g. echo ${test:2}
will just echo "master". Alternatively you could assign it anew as you already proposed:
branch=${test:2}
echo $branch
这将显示大师,就像你想要的。
This will echo "master", like you wanted.
这篇关于如何获取当前的git分支的名称放入一个shell脚本变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!