Wednesday, April 25, 2018

bash - Evaluate each environment variable and set it back in ubuntu


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?


Answer



The following worked for me.


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

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


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...