I'm trying to make a bash script which will print commits ahead of current branch in other branches. However, when I execute command git branch
in a subshell, I get not only branch names but also list of files and folders in the current directory. Why calling $(git branch)
behaves this way?
Asked
Active
Viewed 367 times
3

Tuomas Toivonen
- 21,690
- 47
- 129
- 225
-
maybe in a different directory – Farvardin Sep 18 '16 at 07:49
1 Answers
6
It's not the command substitution, it's the quoting. Here is the result of git branch
on a repo:
$ git branch
5-job-test-fails
* master
revisions
with_cool_background
Notice the askerisk.
When you write echo $(git branch)
, since the argument is unquoted, the asterisk will expand to the files in the current directory:
$ echo $(git branch)
5-job-test-fails app bin cable config config.ru db erd.pdf Gemfile Gemfile.lock Guardfile lib log public Rakefile README.rdoc test tmp vendor master revisions with_cool_background
To overcome this, quote the argument:
$ echo "$(git branch)"
5-job-test-fails
* master
revisions
with_cool_background

user000001
- 32,226
- 12
- 81
- 108
-
Wow, never thought this would be the case. How about if I must build foreach statement which iterates over all the branches? How to deal with the star? – Tuomas Toivonen Sep 18 '16 at 08:35
-
You have to remove the star anyway before processing the branch name. There are a few alternatives on how to do it in this question: https://stackoverflow.com/questions/3846380/how-to-iterate-through-all-git-branches-using-bash-script. It's probably best not to use `git branch` at all in scripts according to the accepted answer there. – user000001 Sep 18 '16 at 08:43