Created
May 18, 2015 00:50
-
-
Save sgviking/ec973ed5b5dbfd01bfc2 to your computer and use it in GitHub Desktop.
Read in environmental variables with env command and output the environmental variables as a JSON string. This was build to be used in a minimal Docker environment with only shell scripting access.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# To use this with sed the output string needs to be escaped like so: | |
# ./env2json | sed -e 's/[]\/$*.^|[]/\\&/g' | |
# Here is an example: | |
# sed -e "s/{PLACEHOLDER}/$(./env2json | sed -e 's/[]\/$*.^|[]/\\&/g')/" test.conf | |
# http://www.linuxjournal.com/content/bash-associative-arrays | |
# http://stackoverflow.com/questions/3112687/how-to-iterate-over-associative-array-in-bash | |
# http://stackoverflow.com/questions/9449417/how-do-i-assign-the-output-of-a-command-into-an-array | |
# http://tldp.org/LDP/abs/html/string-manipulation.html | |
# http://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern | |
declare -A $( env | awk -F'=' '{print "environment["$1"]="$2}' ) | |
json_environment="{" | |
for i in "${!environment[@]}" | |
do | |
json_environment=$json_environment"\"${i}\":\"${environment[$i]}\"," | |
done | |
# remove trailing comma and add finishing curly brace | |
json_environment="${json_environment%,}}" | |
echo -n $json_environment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment