1

I'm trying to write a shell script which reads all the environment variables, evaluate them for included env. variable with in them and re-export after evaluvation.

Example - I've an environment variable exposed like this:

echo $JVM_OPTS                 
-Djava.awt.headless=true -Xmx1600m  -Djava.rmi.server.hostname=${CONTAINER_IP} -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Duser.language=en -Duser.country=US -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -XX:CMSIncrementalDutyCycleMin=0


echo $CONTAINER_IP 
10.44.214.63

Now, I need to eval "JVM_OPTS" variable and substitute the value of ${CONTAINER_IP} in $JVM_OPTS to 10.44.214.63. Finally, set this evaluated value back in JVM_OPTS variable.

Sample Output:

echo $JVM_OPTS                 
    -Djava.awt.headless=true -Xmx1600m  -Djava.rmi.server.hostname=10.44.214.63 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Duser.language=en -Duser.country=US -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -XX:CMSIncrementalDutyCycleMin=0

My Analysis so far: I wrote the below code to do the task

#!/bin/bash

for path in $(printenv); do
    path=`eval echo $path`
    echo $path
done

printenv would give the entire env. variable along with values. I just need the name and then use the value.

How to achieve this?

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
  • 1
    Where/when is `JVM_OPTS` being assigned? Can you not just arrange for `CONTAINER_IP` to be set *before* `JVM_OPTS` is assigned so that it can expand the value normally? – Etan Reisner Apr 06 '16 at 11:15
  • No. Actually CONTAINER_IP is being sent as an argument to Docker run. While the variable JVM_OPTS is being set when the Docker is being compiled. So until run time I won't know the value of CONTAINER_IP. – Kishore Bandi Apr 06 '16 at 11:27
  • You could append to the pre-set `JVM_OPTS` with the `CONTAINER_IP` value at boot time even if the rest of the value is set at image creation time. – Etan Reisner Apr 06 '16 at 11:42
  • also asked at http://superuser.com/q/1062094/4714 – glenn jackman Apr 06 '16 at 13:06

1 Answers1

2

Try

for path in $(compgen -e) ; do
    eval "$path=\"${!path//\"/\\\"}\""
done

But see Why should eval be avoided in Bash, and what should I use instead? for information about the pitfalls of using eval.

compgen -e prints a list of the environment variables.

${!path} evaluates to the value of the variable whose name is $path.

//\"/\\\" replaces " with \" in the variable value, to preserve embedded double quotes.

Community
  • 1
  • 1
pjh
  • 6,388
  • 2
  • 16
  • 17