I am running a loop for an array of variables that generates three more variables.


for foo in ${bar[@]};
    do bar1=$(echo $foo | awk '{print$1}');
       bar2=$(echo $foo | awk '{print$2}');
       bar3=$(echo $foo | awk '{print$3}');

However when the loop is finished I need the three newly created variables to become arrays themselves that I can run for loops on as well.


for foo in ${bar1[@]}
    do echo $foo

^^^^this should show multiple lines.

can anyone provide anyway to make this possible?

  • Post how does bar array looks like, and what is desired output in bar1,bar2,bar3. – jimmij Aug 27 '15 at 0:27


      bar1+=($(echo $foo | awk '{print$1}'))

i.e., variable+=( value ) to add a value to an array.  Of course the code to use the bar1 array has to look something like

for foo in "${bar1[@]}"
    echo "$foo"

Of course you should always quote shell variables (e.g., "$foo" and "${bar1[@]}") unless you have a good reason not to, and you’re sure you know what you’re doing. 


No need for three pipelines here; just use read to extract the first three fields from the string.

for foo in "${bar[@]}"; do
    read bar1 bar2 bar3 the_rest <<< "$foo"

the_rest is only necessary if there's a chance that foo could be something like "a b c d" and you don't want bar3 to be set to c d.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.