Search code examples
bashgitbranch

Retrieving git branches in a bash array


I would like to list all git branches which name contain a certain string in an array on a bash script. Seems I can do it to some degree, it just does not look like an array. This is what I've tried:

param1="feature"

branches=$(git branch | cut -c 3- | grep $param1);
echo $branches;
echo ${branches[0]};

I would like the output to be:

feature/my_branch_1 feature/my_branch_2 feature/my_branch_3
feature/my_branch_1

I get instead:

feature/my_branch_1 feature/my_branch_2 feature/my_branch_3
feature/my_branch_1 feature/my_branch_2 feature/my_branch_3

Solution

  • To assign to an array, you need to use parentheses.

    branches=($(git branch | cut -c 3- | grep feature))
    #        ~                                        ~