I need to run a git branch command in a child process, but I want to get only the currently checked out branch. This command work in terminal:
git branch | grep \* | cut -d ' ' -f2
I have a number of posts that are trying to do something similar, but my understanding of Unix commands isn't good enough to get a solution.
I have tried this among a number of other things:
spawn("git", ["branch | grep \* | cut -d ' ' -f2"], opts)
this is what I . get from stderr:
git: 'branch | grep * | cut -d ' ' -f2' is not a git command. See 'git --help'.
Shell commands have a lot of syntax: a | b | c
doesn't mean "run the command a | b | c
" but rather "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".
You could duplicate all of this glue in your code, but git branch | grep \* | cut -d ' ' -f2
is the wrong way to do this in the first place. Instead, use one of these two commands:
git symbolic-ref --short HEAD
git rev-parse --abbrev-ref HEAD
The difference between these two commands is that the first one fails (with an error message) if there is no current branch. The second one prints HEAD
for this case. This case occurs when HEAD
is "detached", i.e., the repository has no current branch.
The git branch | grep \* | cut ...
sequence succeeds but prints (HEAD
for this detached-HEAD case, and (HEAD
is not useful.