Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;

The script executes as expected:

$ ./script.ksh

However if I replace the loop with this:

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

I execute it and this is what I get:

$ ./script.ksh bar

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

share|improve this question
up vote 2 down vote accepted

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;;
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 …
share|improve this answer
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
share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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