问题描述
我是 shell 脚本的新手,无法弄清楚这一点.如果你不熟悉,命令 git branch 会返回类似
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
,结果只是目录中的文件列表.我们如何让 test="* develop" 的值?
, the result is just a list of files in the directory. How do we make the value of test="* develop"?
然后下一步(一旦我们将* 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.
推荐答案
* 被扩展,你可以做的是使用 sed 代替 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')
和 Noufal Ibrahim 建议的使用 git 符号引用的版本
And a version using git symbolic-ref, as suggested by Noufal Ibrahim
branch=$(git symbolic-ref HEAD | sed -e 's,.*/(.*),1,')
为了详细说明扩展,(正如 marco 已经做过的那样)扩展发生在 echo 中,当您使用包含 的
然后echo $test
执行 echo $test
* master*
按照正常的扩展规则进行扩展.要抑制这一点,必须引用变量,如 marco 所示:echo "$test"
.或者,如果你在回显之前去掉星号,一切都会好起来的,例如echo ${test:2}
只会回显 master
.或者,您可以按照您已经提出的建议重新分配它:
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
这将像您想要的那样回显 master
.
This will echo master
, like you wanted.
这篇关于如何将当前 git 分支的名称放入 shell 脚本中的变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!