This answer states that to find out the current branch name of a git repo, we can do
这个答案指出,要找出Git回购的当前分支名称,我们可以这样做
git rev-parse --abbrev-ref HEAD
Now, this works for me, and I want to use this command when pushing to git, i.e. I want first to find out the branch name and then push to that branch, so I wrote the following bash function into my .bashrc
file:
现在,这对我有效,我想在推送到git时使用此命令,也就是说,我希望首先找到分支名称,然后推送到该分支,因此我将以下bash函数写入我的.bashrc文件:
function bname() {
branch="git rev-parse --abbrev-ref HEAD"
command git push origin "$branch"
}
After doing source .bashrc
, executing typing bname
in the terminal results in
在执行完源文件.bashrc之后,执行在终端中键入bname会导致
fatal: invalid refspec 'git rev-parse --abbrev-ref HEAD'
How do I need to modify my bash function? Thanks.
如何修改我的bash函数?谢谢.
EDIT: To exectute the command branch
, I tried sth like this:
编辑:为了执行命令分支,我尝试了如下命令:
function bname() {
branch= command "git rev-parse --abbrev-ref HEAD"
command git push origin $branch
}
but this results in the error
但这导致了错误
git rev-parse --abbrev-ref HEAD: command not found
[...]
更多回答
You're storing the string with the command in the variable - not running it.
您将字符串与命令一起存储在变量中--而不是运行它。
cf. the edit I made
参见我所做的编辑
Same issue - you have to run the rev-parse commandi n a subscell if you want to store the output of the command.
同样的问题-如果您想要存储命令的输出,则必须在子单元中运行rev-parse命令。
could you quickly post an answer?
你能不能快点给我回复?
Why do you need this command? git push origin HEAD
does the same
为什么需要这个命令?Git推送原点磁头也是如此
优秀答案推荐
For the output of a command to be saved in a variable you need to use subshells
要将命令的输出保存在变量中,您需要使用子外壳
For example:
例如:
variable=$( ls )
would store the output written by ls
to stdout in the indicated variable.
将ls写入stdout的输出存储在指定的变量中。
branch="git rev-parse --abbrev-ref HEAD"
You should be using command substitution:
您应该使用命令替换:
branch="$(git rev-parse --abbrev-ref HEAD)"
Bash will run the command within $(...)
and replace with the command's output. Incidentally, these days the $(...)
format is preferred to backticks.
Bash将在$(...)内运行该命令并替换为命令的输出。顺便说一句,这些天来,$(...)格式优先于反标记。
EDIT: To exectute the command branch, I tried sth like this:
...
branch= command "git rev-parse --abbrev-ref HEAD"
You really can't guess your way through bash syntax. I highy recommend you read a tutorial or two.
你真的不能通过bash语法来猜测。我强烈建议你读一两本教程。
更多回答
its good practice to surround that with double quotes
最好用双引号将其括起来
我是一名优秀的程序员,十分优秀!