3

I'm using Ksh88 on a Solaris 10 machine.

If I do the following:

foo="one two three"
for i in $foo; do
    echo $i;
done

The script executes as expected:

$ ./script.ksh
one
two
three

However if I replace the loop with this:

foo="one two three"
for i in $(sed -e 's/bar/$foo/' <(echo $1));
do
    echo $i
done

I execute it and this is what I get:

$ ./script.ksh bar
$foo

How can I make for expand the result of the sed command into a variable?

2

sed -e 's/bar/$foo/' <(echo $1) prints $foo. The result of a command expansion is not subject to shell syntax processing. It is only subject to field splitting (splitting into words) filename generation (i.e. globbing), when you use it this way outside double quotes.

In any shell, if you have the name of a variable in another variable, you can obtain the value of that variable with eval.

variable_name=$(sed -e 's/bar/foo/' <(echo $1))
case $variable_name in
  *[!0-9A-Z_a-z]*) echo 1>&2 "Invalid variable name: $variable_name"; exit 3;;
esac
eval variable_value="\${$variable_name}"
for i in $variable_value; do …

Note that $variable_value not only breaks up the value into whitespace-delimited parts, but also performs globbing (i.e. expands wildcards into file names) on the parts. To turn off globbing, call set +f beforehand.

In ksh93, there is a special flag you can use when defining a variable var, which tells the shell that the value of the variable is itself a variable name and that $var must expand to the value of the variable whose name is $var. Also, you should make foo an array, since it's really a list of strings and not a string.

foo=(one two three)
typeset -n variable_name="$(sed -e 's/bar/foo/' <(echo $1))"
for i in "${variable_name[@]}"; do …
0
foo=$(echo "$foo" | sed 's/[\\\/]/\\&/g') # only required if $foo can contain one of \/
set +f     # only required if $foo contains one of \[*?
for i in $(echo "$1" | sed -e "s/bar/$foo/"); do
    echo $i
done
  • Yuck. What if $foo contains a /? – Gilles Feb 21 '12 at 23:48
  • There is no indication it can contain / in the OP question but I'm taking your point into account anyway. – jlliagre Feb 24 '12 at 6:24

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.