3

I'm trying to get from my git repo all branches (git branches -a) that matches regex (grep xxx).

Normally in command line I write this:

git branch -a | grep xxx

So I'm trying to do the same in .sh file:

  1. get all branches that matches regex
  2. split it into array
  3. get first branch

Below is my code:

#!/bin/bash

branches=( $(git branch -a | grep $1) )

echo branches : $branches
echo branch : ${branches[0]}

Sadly it somehow add all files in my current folder.

This is the output:

$> checkout.sh 2887
branches : ant 
branch : ant 

If I change branches=( $(git branch -a | grep $1) ) to branches=$(git branch -a | grep $1) I got all files in my dir and branches at the end

love
  • 2,823
  • 2
  • 14
  • 32
MAGx2
  • 2,955
  • 6
  • 28
  • 52

1 Answers1

8

Etan has the simple approach in his comment.

You error may be happening because you fail to quote $1, so if you're passing a regular expression with wildcards (like script 'release-.*'), the shell will examine the variable before handing it off to grep -- word splitting and filename expansion will occur. You must quote variables whenever you don't absolutely control the contents.

Also, no reason to store the results in an array just to grab the first result, let grep handle that:

first_match=$( git branch -a | grep -m 1 "$1" )

But use git branch -a --list pattern

glenn jackman
  • 207,528
  • 33
  • 187
  • 305