Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through all the ENV variables printing key and value?

Tags:

bash

I'd like to iterate through the variables in env printing:

name: ${name} value: ${value}

Simply splitting by line break and iterating does not work, because of multi-line values, e.g.

SERVER_TLS_SERVER_CRT=-----BEGIN CERTIFICATE-----
foo
-----END CERTIFICATE-----

The use case is to workaround Docker limitation that restricts passing multi-line variables via --env-file.

like image 298
Gajus Avatar asked Sep 16 '16 10:09

Gajus


2 Answers

Old thread, I know. But for anyone else needing a solution in sh and without -0 support for env:

env | while IFS= read -r line; do
  value=${line#*=}
  name=${line%%=*}
  echo "V: $value"
  echo "N: $name"
done
like image 73
siiikooo0743 Avatar answered Sep 28 '22 03:09

siiikooo0743


Here's the solution from #bash.

unset IFS
args=() i=0
for var in $(compgen -e); do
    printf -v 'args[i++]' -e%s=%s "$var" "${!var}"
done

I initially thought the idea was to output, hence printf %q was necessary, but that's not the case when just building an arguments array, so it can be simplified to this:

unset IFS
args=()
for var in $(compgen -e); do
    args+=( "-e$var=${!var}" )
done
like image 38
geirha Avatar answered Sep 28 '22 04:09

geirha