Bash - concatenate string - strange variable scoping

Hello,

I am trying to concatenate a string in a bash script like this:

runCmd="docker run -e \"IMAGE_NAME=$IMAGE_NAME\" "

env | grep "$ENV_SUFFIX" | while read line; do
  envCmd="-e \"${line}\" "
  runCmd=$runCmd$envCmd
  echo $runCmd # here concatenation works fine
done

echo $runCmd # here concatenation disappears

Inside the loop, concatenation works fine, however when I try to echo the result outside of it, it disappears. Any idea how to make it work in bash? Thanks a lot

Hi,
Your problem is the pipe ( '|' ) that create another process to execute your filter.
In bash, you can change your syntax like this (but not posix) :

runCmd="docker run -e \"IMAGE_NAME=$IMAGE_NAME\" "
while read line; do
   envCmd="-e \"${line}\" "
   runCmd=$runCmd$envCmd
   echo $runCmd # here concatenation works fine
done < <(env | grep "$ENV_SUFFIX" )
echo $runCmd # here concatenation disappears

Regards.

1 Like

Works, thanks a lot.

In POSIX, it is unspecified whether or not the last stage of a pipeline is run in the current shell execution environment. (In ksh it is and the script in post #1 would work without change; in bash it is not and the value of a variable set in the last stage of the pipeline disappears when the pipeline completes execution.)

With any POSIX conforming shell, you could modify disedorgue's suggestion to:

runCmd="docker run -e \"IMAGE_NAME=$IMAGE_NAME\" "
while read line; do
   envCmd="-e \"${line}\" "
   runCmd=$runCmd$envCmd
   echo $runCmd # here concatenation works fine
done <<EOF
$(env | grep "$ENV_SUFFIX")
EOF
echo $runCmd # and concatenation works here too

and get what you want.