views:

95

answers:

5

I am new to shell scripting and can't figure this out. If you are unfamiliar, the command git branch returns something like

* develop
  master

, where the asterisk marks the currently checked out branch. When I run the following in the terminal:

git branch | grep "*"

I get:

* develop

as expected.

However, when I run

test=$(git branch | grep "*")

or

test=`git branch | grep "*"`

And then

echo $test

, the result is just a list of files in the directory. How do we make the value of test="* develop"?

Then the next step (once we get "* develop" into a variable called test), is to get the substring. Would that just be the following?

currentBranch=${test:2} 

I was playing around with that substring function and I got "bad substitution" errors a lot and don't know why.

A: 

Try this blog post.

DaDaDom
+3  A: 

The * is expanded, what you can do is use sed instead of grep and get the name of the branch immediately:

branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')

And a version using git symbolic-ref, as suggested by Noufal Ibrahim

branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

To elaborate on the expansion, (as marco already did,) the expansion happens in the echo, when you do echo $test with $test containing "* master" then the * is expanded according to the normal expansion rules. To suppress this one would have to quote the variable, as shown by marco: echo "$test". Alternatively, if you get rid of the asterisk before you echo it, all will be fine, e.g. echo ${test:2} will just echo "master". Alternatively you could assign it anew as you already proposed:

branch=${test:2}
echo $branch

This will echo "master", like you wanted.

wich
It would be courteous of you to mention my answer if you used elements from it to update yours.
Noufal Ibrahim
Of course, my apologies, I updated quickly before leaving, missed the attribution.
wich
+5  A: 

I would use the git-symbolic-ref command in the git core. If you say git-symbolic-ref HEAD, you will get the name of the current branch.

Noufal Ibrahim
+1 for `git-symbolic-ref` ;)
VonC
In later version of git, you will have to use git symbolic-ref HEAD instead.
Jamey Hicks
+1  A: 

disable subshell glob expansion,

test=$(set -f; git branch)
Dyno Fu
that's not where the expansion happens, it's in the echo, as marco already elaborated upon.
wich
+4  A: 

The problem relies on:

echo $test

In fact the variable test contains a wildcard which is expanded by the shell. To avoid that just protect $test with double quotes:

echo "$test"
marco
+1 for the best answer.
Dennis Williamson