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


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

Sample Output:

echo $JVM_OPTS                 
    -Djava.awt.headless=true -Xmx1600m  -Djava.rmi.server.hostname= -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


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

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

How to achieve this?


Basically, the solution is in your question: eval.

eval export JVM_OPTS=\"$JVM_OPTS\"
  • Yes, JVM_OPTS=eval echo $JVM_OPTS Also gave me the same output. But the problem is with the script. I managed to extract each env. variable, but unable to get its actual value. – Bandi Kishore Apr 6 '16 at 11:32
  • @BandiKishore - This answer appears to answer your question, and very simply, without any loops. If you require to know how to parse the printenv output, you should rephrase your question. If that is what you need, then the following illustrates the parsing: printenv|while l=$(line); do echo ${l%%=*} is set to ${l#*=}; done. – AFH Apr 6 '16 at 11:53

The following worked for me.

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

As posted at https://stackoverflow.com/a/36449824/1925997

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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