2

i am trying to make output of a command be read by a for loop, but in such a way that the loop variable would be an array. is that possible? this is what I've been trying so far:

function samplevals() {
    echo '"aa bb"'
    echo '"cc dd"'
    echo '"ee ff" "gg hh"'
}

samplevar='"aa bb"
"cc dd"
"ee ff" "gg hh"'

echo call function samplevals:
for x in `samplevals `; do echo ">$x<"; done

echo read variable samplevar:
echo $samplevar
for x in $samplevar; do echo ">$x<"; done

echo process output of 'echo samplevar:'
for x in `echo $samplevar`; do echo ">$x<"; done

echo "the thing with set"
for x in $samplevar; do set -- $x ; echo "\$1=>$1<,\$2=>$2<"; done

but the output is always the same:

>"aa<
>bb"<
>"cc<
>dd"<
>"ee<
>ff"<
>"gg<
>hh"<

Can I somehow prevent bash from splitting the elements into smaller pieces?

1
  • The quotes are literal data, not syntactic quotes. You don't have any arrays in your code. Commented Jan 11, 2017 at 13:24

2 Answers 2

1

Along the lines of chepner's answer, using read command. The -a flag part of the command lets the output to written out to an array.

IFS=$'\t' read -ra arrayDef < <(echo -ne '"abc def"\t"ghi jkl"')
for x in "${arrayDef[@]}"; do
    echo ">$x<"
done

You can replace the echo part with some command that generates such a string. Remember to update the IFS appropriately as to how the string is de-limited. In my case, I just a have the string de-limited by \t

Sign up to request clarification or add additional context in comments.

2 Comments

This just shifts the "delimiter" from arbitrary whitespace to a tab specifically. It doesn't solve the underlying problem of having a separator that is guaranteed not to occur in an element of the array.
@chepner: Initially provided this as alternative complementing logic on seeing yours, but on seeing OP not approving of yours. Do you want me to delete it
1

The way to define an array in bash is

samplevars=("aa bb" "cc dd" "ee ff" "gg hh")
for x in "${samplevars[@]}"; do
    echo ">$x<"
done

2 Comments

There is no simple way to create an array from command output, because there is no such thing as an array value in bash, only array parameters whose syntax gives the appearance of array values. An array is really closer to a loosely related set of individual variables, tied together with some syntactic sugar.
This almost works. Change samplevars to samplevar on the first line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.