Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate variable into single variable separated by comma with for loop

Tags:

linux

bash

shell

I want to add the values to a variable, separated by comma, using for loop. First values should remain first and so on.

for ((i=0; i<${#MYARRAY[@]}; i++));
do
  ALL=$ALL$MYARRAY$i,
done
echo $ALL

I expect the output val1,val2,val3 but the actuel output is val1,val2,val3,

How to avoid the comma after the last value?

like image 757
user11647113 Avatar asked Oct 27 '25 09:10

user11647113


1 Answers

Just add one of the three statements after your for loop:

  1. ALL=${ALL%,}

  2. ALL=${ALL::-1}

  3. ALL=${ALL%?}

like image 148
Davis080498 Avatar answered Oct 30 '25 00:10

Davis080498



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!