Echo/Printf environment key/value upon creation

70 views Asked by At

I'm using bash 4, and setting a few vars (each beginning MIH_) similar to:

: "${MIH_POD_NAME:=$(kubectl get pods --namespace mih -l "app.kubernetes.io/name=mih,app.kubernetes.io/instance=mih" -o jsonpath="{.items[0].metadata.name}")}"

I want to know if its possible to print the details of these environment variable to stdout inline as they're created, rather than having to create them all, then separately iterate over them afterwards, using:

for var in "${!MIH_@}"; do
   logger $(printf '%s=%s\n' "$var" "${!var}")
done

Output:

INFO  MIH_POD_NAME=mih-8695f87c8c-t5klb

(Note, logger is a function I've written that takes a string and formats it for a nice output.)

Adding an echo before the : only prints the value after a colon: : mih-8695f87c8c-t5klb


I managed to achieve this somewhat by adding:

; eval "logger $(printf '%s=%s\n' MIH_POD_NAME $MIH_POD_NAME)"

to the end of each command. But I wonder if there is a more dynamic way of achieving this?

1

There are 1 answers

3
mandy8055 On BEST ANSWER

You can make use of declare to achieve your purpose.

We can use an associative array option(-A) to store the variable names as keys and the corresponding commands as values. Something like:

declare -A MIH_VARS=(
  ["MIH_POD_NAME"]="kubectl get pods --namespace mih -l 'app.kubernetes.io/name=mih,app.kubernetes.io/instance=mih' -o jsonpath='{.items[0].metadata.name}'"
  ["MIH_VAR_1"]="echo '8080'"
  ["MIH_VAR_2"]="cmd_to_get_other_port_no"
)

for var in "${!MIH_VARS[@]}"; do
  declare -g "${var}=$(${MIH_VARS[$var]})"
  logger "$(declare -p ${var})"
done

DEMO