在需要管道的子进程中尝试 运行 git 命令

Trying to run a git command in a child process that requires pipes

我需要在子进程中 运行 一个 git 分支命令,但我只想获取当前签出的分支。此命令在终端中工作:

git branch | grep \* | cut -d ' ' -f2

我有很多帖子都在尝试做类似的事情,但我对 Unix 命令的理解还不够好,无法找到解决方案。

我已经尝试了很多其他的东西:

spawn("git", ["branch | grep \* | cut -d ' ' -f2"], opts)

这就是我。从标准错误获取:

git: 'branch | grep * | cut -d ' ' -f2' is not a git command. See 'git --help'.

Shell 命令有很多语法:a | b | c 并不意味着 "run the command a | b | c" 而是 "run the command a, with a bunch of glue that makes it pipe output; run the command b, with a bunch of glue that makes it read the earlier piped output as its input, and pipe its output; and run the command c, with a bunch of glue that makes it read b's piped output".

您可以在代码中复制所有这些胶水,但 git branch | grep \* | cut -d ' ' -f2 首先是错误的方法。相反,使用以下两个命令之一:

git symbolic-ref --short HEAD
git rev-parse --abbrev-ref HEAD

这两个命令的区别在于第一个失败(带有错误消息)如果没有当前分支。对于这种情况,第二个打印 HEAD 。这种情况发生在 HEAD 为 "detached" 时,即存储库 没有当前分支

git branch | grep \* | cut ... 序列 成功但打印 (HEAD 对于这种分离的 HEAD 情况,(HEAD 没有用。