Bash – Making a function that displays a variable’s name and its value

bashshellshell-scriptvariable

I want to write function (let's call it superEcho) that takes a variable name as input. The function should print that variable's name and its value

function superEcho
{
     echo "$1: ?????"
}

var=100

superEcho var

I want this script to return

var: 100

But I don't know what should I put instead of "?????" in the superEcho function.

Best Answer

POSIXly:

superEcho() {
  eval 'printf "%s\n" "$1: ${'"$1"'}"'
}

Like for the bash-specific ${!var}, that expects $1 has been sanitized and contains a valid variable name. Otherwise, that amounts to an arbitrary command injection vulnerability.

You could do the sanitization in the function:

superEcho() {
  case $1 in
    ("" | *[!_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]* | [0123456789]*)
      printf >&2 'Invalid variable name: "%s"\n' "$1"
      return 1;;
    (*) eval 'printf "%s\n" "$1: ${'"$1"'}"'
  esac
}

Note that for variables of type array or associative array, in bash or ksh (POSIX sh has no array except "$@" which you couldn't use here as that would be the arguments of the superEcho function itself) that only prints the value of the element of indice 0, while in zsh, that would output the concatenation of the values with the first character of $IFS (and with SPC characters in yash).

In ksh, zsh, bash or yash (the 4 Bourne-like shells with array support). See also typeset -p var to print the definition and attributes of a variable.