Check if git branch exists in bash: weird interpolation behavior

I am trying to check if any branch exists in a shell script.

However, git-branch seems to modify its result on interpolation. (I do not know the exact phenomenon or terminology here)

For example, I'm trying to get an 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 

Something like ls-files seems to be interfering. How so? Is this a bash? Git? I'm confused.

+4
source share
2 answers

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

 $ git branch develop * master 

Running only echo * in your shell will print the globe of your working directory:

 compiler.sh HOSTNAME index.html 

So, your original problem comes from the fact that after the extension, you actually use echo develop * master .

To avoid this swap behavior, you can simply specify a strong quote from branches during echo :

 $ branches=`git branch` $ echo "$branches" develop * master 
+6
source

Try to do this:

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

I recommend using sed because the * character is glob for the shell , so it applies to all files and directories in the current directory. Moreover, I remove unnecessary extra spaces.

+3
source

Source: https://habr.com/ru/post/1444684/


All Articles