0

I have a directory with git inside and git branch gives me the following output:

$ git branch
  branch1
* branch2
  master

The * marks the current branch. I would like to use this output in a script. So I loop over the lines like this:

$ for line in $(git branch); do echo "${line}"; done;
branch1
README.txt
branch2
master

Questions:

What happened to the * and why do I see README.txt[1]?

How can I loop over the lines returned by a normal git branch exactly as they are, with * and a space?

P.S.: I am on a Mac right now.

[1] (or any other file in the repository but this one only has one file "README.txt")

2

When $(git branch) is expanded for the for loop to loop over it, it expands to the multi-line string

  branch1
* branch2
  master

Since the command substitution is unquoted, this is then split on spaces, tabs and newlines (by default) into the four words

branch1 * branch2 master

Each word then undergoes filename generation (globbing). The second word, *, will be replaced by all filenames in your current directory. This appears to be one file only, README.txt.

The final list that the loop will loop over is therefore

branch1 README.txt branch2 master

Instead, if you just want to output this in a script, use

git branch

without doing anything more.

If you want to save the output in a variable, use

branches=$( git branch )

Would you want to get the name of the current branch, then extract the branch whose name is preceded by a *:

curr_branch=$( git branch | awk '/^\*/ { print $2 }' )

Would you want to iterate over the output of git branch, use a while loop:

git branch |
while read -r star name; do
    if [ -z "$name" ]; then
        name=$star
        printf 'One branch is "%s"\n' "$name"
    else
        printf 'The current branch is "%s"\n' "$name"
    fi
done
  • git rev-parse --abbrev-ref HEAD to show only current branch. – pfnuesel Mar 6 at 15:46
  • 1. Reason I do this I want to also do a $(git config branch.$line.description) and append it to the branch name, but I also want to keep the asterisk. 2. Thank you for this excellent write up! – scrrr Mar 6 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.