0

I am trying to add elements to an array in bash. I am querying and looping over the query.

delete_arr=()
delete_arr+=("test")
mysql -e "$sql_statement" | while read directory_name; do 
if [ $counter -gt 0 ]
   then
     delete_arr+=($directory_name)
fi
let counter=counter+1
done

 for i in "${delete_arr[*]}"; do echo "$i"; done

The only output I am getting is test. I should be getting a lot more data. The query works and the data gets added to the array in the loop however when I jump out of the loop the array only contains test.I am doing nothing to reset the array.

newdeveloper
  • 534
  • 3
  • 17

1 Answers1

1

In the pipe, you are implicitly creating a new subshell with its own namespace. Try avoiding the pipe:

delete_arr=()
delete_arr+=("test")
while read directory_name
do 
    if [ "$counter" -gt 0 ]
    then
        delete_arr+=("$directory_name")
    fi
    counter=$((counter+1))
done < <(mysql -e "$sql_statement")

for i in "${delete_arr[@]}"; do echo "$i"; done
Poshi
  • 5,332
  • 3
  • 15
  • 32