0

I am trying to insert values in to an array in a loop as follows:

branches_to_delete=()
cat branches.txt | while read branch_name
do
   BRANCH_COUNT=$(git ls-remote | grep -w $branch_name | wc -l)
   if [ $BRANCH_COUNT -eq 0 ]; then
     echo "Branch does not exist"
     branches_to_delete+=($branch_name)
   elif [ $BRANCH_COUNT -eq 1 ]; then
     echo "Branch exists"
   else 
     echo "Not valid result"
   fi
done

echo "Loop finished"
echo ${branches_to_delete[@]}

But when I printout branches_to_delete it is actually empty. What am I doing wrong here?

madu
  • 5,232
  • 14
  • 56
  • 96
  • 1
    Why do you need an array anyway? Just do `git ls-remote | sed -n 's%.*refs/heads/%%p' | grep -xFf - branches.txt` – tripleee Feb 01 '21 at 12:37

1 Answers1

1

With the pipe from cat branches.txt into the read loop, you create a subshell that cannot access the parent shell's branches_to_delete array.

You can fix this by avoiding the pipe and saving a useless use of cat:

branches_to_delete=()
while read branch_name; do
  ...
done < branches.txt

(Make sure nothing in ... reads from read's stdin. You'll notice if something is missing).

Jens
  • 69,818
  • 15
  • 125
  • 179