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")

1

1 Answer 1

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 (non-hidden) filenames in your current directory. This appears to be the name of one file only in your case, 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

You may also use git branch --show-current to get the name of the current branch directly.

4
  • git rev-parse --abbrev-ref HEAD to show only current branch.
    – pfnuesel
    Mar 6, 2019 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, 2019 at 16:07
  • Unless someone has tweaked options, * expands to all non-hidden (i.e. non-dot) entries. Not all dirs have dotfiles other than the special . and .. but git'ed projects usually do. Sep 18, 2019 at 10:30
  • @dave_thompson_085 Thanks, I believe I have clarified that bit now.
    – Kusalananda
    Sep 18, 2019 at 10:31

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