0

When the git branch command is executed it usually shows:

* main 
.... # other branches

Having the following through command substitution and string substitution work as expected:

current_branch=$(git branch | head -n1)     #1
current_branch="${current_branch/* /}"      #2  
echo "current_branch: '${current_branch}'"

prints only main

Question:

How to merge (if is possible) lines 1 and 2 in one?

current_branch=$(git branch | head -n1 | XXX)

What should be XXX?

2
  • 1) the ${var/pattern/replacement} expansion doesn't take a regex, but a shell glob pattern. 2) does it matter if that's on two lines or one?
    – ilkkachu
    Commented Feb 22, 2022 at 13:06
  • @ilkkachu updated the post - just for presentation purposes I created this post. So is not critical have all in 1 line. Commented Feb 22, 2022 at 13:25

2 Answers 2

1

You can't do this with parameter expansion. After all, parameter expansion works on parameters.

You won't always have "main" being the first branch shown. I'd suggest

git branch | sed -n 's/^[*] //p'

However, there's another way to get the current branch (the branch of the HEAD commit) without having to process the output.

git rev-parse --abbrev-ref HEAD
1

The "${current_branch/* /}" expansion returns the value of current_branch with everything up to the last space removed. It's the same as "${var##* }". If you want, you can do the same in sed (for each line, for input from stdin): sed -e 's/.* //'. Here, it might make sense to do that, since you already have a command substitution that sets the value of the variable, and you can add the sed to the pipeline.

Actually, you can use sed to replace head too:

current_branch=$(git branch | sed -e 's/.* //'  -e 1q)

On the other hand, you could do both with the shell's parameter expansions:

current_branch=$(git branch)
current_branch=${current_branch%%$'\n'*}    # remove from first NL
current_branch=${current_branch##* }        # remove to last SP

In zsh, you could cascade the expansions, e.g. with

current_branch=${"$(git branch | head -n1)"/* /}

but that doesn't work in Bash.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .