0

I have a function myFunction() that shall take an integer variable from outside, print it and then increment it.

This works:

myFunction:
myFunction() {
    local var="${1}"
    eval "printf '%s\n' \$$var"
    eval "$var=$(($var+1))"
}

But, I don't want to use eval in this as a user of this function might enter a wrong variable name that might then be executed. I would like to use something like printf -v as it would make the usage safer.

How can I do this?

TimFinnegan
  • 583
  • 5
  • 17
  • 2
    The linked duplicate's answers are overkill for this case. Just use `myFunction() { printf '%s\n' "${!1}"; (($1++)); }` -- Indirect variable reference + the fact that `$` refs are expanded first in arithmetic expressions takes care of it. – Gordon Davisson Dec 20 '20 at 09:25
  • @GordonDavisson Thanks a lot! This works just fine! Could you post it as an answer, I would like to accept it! – TimFinnegan Dec 20 '20 at 09:41

1 Answers1

0

You can (only?) do this without eval if you are happy enumerating all possible variable names.

myFunction () {
  case $1 in
  (frobme)    printf '%s\n' $frobme; : $((++frobme));;
  (zapme)     printf '%s\n' $zapme;  : $((++zapme));;
  (*)         printf 'invalid name: %s\n' "$1" >&2;;
  esac
}
Jens
  • 69,818
  • 15
  • 125
  • 179