ruxtain
ruxtain

Reputation: 194

Shell: print both variable name and value?

Let's say I have a function called superEcho. I want it to print both the variable name and its value.

#!/bin/bash


function superEcho() {
    echo "${v_day}"
    echo '${v_day}'
}

v_day=20220101
superEcho ${v_day}

# output
# 20220101
# ${v_day}

From the code above, I can easily get the argument name "${v_day}" and its value. However, what if I change the variable's name? Such as:

v_last_day=20211231
superEcho ${v_last_day}

This function won't work any more. Can I change it to adapt to any variable name?

PS: this is a wrapper function, it won't ask users to change their code. For example, you can't pass the variable name as an argument:

superEcho "${v_day}" '${v_day}'

Upvotes: 2

Views: 1732

Answers (1)

Manfred
Manfred

Reputation: 3142

Bash supports indirect parameter expansion using ${!parameter}, which you can use with the name of your variable:

#!/bin/bash

superEcho() { 
  echo "$1 = ${!1}"
}

v_day=20220101
superEcho v_day

(Note that your version of superEcho does not use the passed parameter, but prints v_day in any case.)

Upvotes: 5

Related Questions