2

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

i.e

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

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.

i.e.

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

^^^^this should show multiple lines.

can anyone provide anyway to make this possible?

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

Use

      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[@]}"
do
    echo "$foo"
done

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. 

0

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"
done

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.