Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if git branch exists in bash: weird interpolation behavior

I'm trying to see if a certain branch exists within a shell script.

However, git-branch seems to modify its output when interpolated. (I don't know the exact phenomenon or terminology here)

For example, I'm trying to get the array of branches:

$ git branch
  develop
* master

$ branches=`git branch`
$ echo $branches
develop compiler.sh HOSTNAME index.html master

$ echo `git branch`
develop compiler.sh HOSTNAME index.html master

A kind of ls-files seems to be getting in the way. How come? Is this Bash? Git? I'm confused.

like image 339
Jonathan Allard Avatar asked Jan 15 '23 02:01

Jonathan Allard


2 Answers

The output of git branch contains the * character, which signifies your current branch:

$ git branch
develop
*  master

Running just echo * in your shell will print a glob of your working directory:

compiler.sh HOSTNAME index.html

So your original problem arises because, after expansion, you're actually running echo develop * master.

To avoid this directory-globbing behavior, you could just strong-quote branches during echo:

$ branches=`git branch`
$ echo "$branches"
develop
*  master
like image 76
pje Avatar answered Jan 23 '23 19:01

pje


Try doing this :

branches=$(git branch | sed 's/\(\*| \)//g')

I recommend you to use sed, because the * character is a glob for the shell, so it's expanded to all files and dir in the current directory. Moreover, I remove not needed extra spaces.

like image 27
Gilles Quenot Avatar answered Jan 23 '23 20:01

Gilles Quenot