0

How can I pass a variable name to a function and use it outside its scope?

I tried this but it doesn't work:

questionPrompt() {
    while [ -z "$answer" ]; do
    echo $1
    read answer
    ${2}=$answer
    done
}

questionPrompt "Which color do you like?" "COLOR"

echo $COLOR

It says: COLOR=red: command not found

KaMZaTa
  • 535
  • 2
  • 9
  • 24

1 Answers1

1

Use declare:

declare -g "$2=$answer"

or

declare -gn var=$2
var="$answer"

However, the version of bash that ships with macOS (3.2) doesn't support declare -g; you can use printf instead.

printf -v "$2" '%s' "$answer"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • It seems to work but it put me on exit and I can run anymore any other function call e.g. `questionPrompt "Which color do you like?" "SIZE"` – KaMZaTa Jul 13 '20 at 17:05
  • `answer` is global as well, so the second time you call it, `answer` is already non-empty, so the loop is never entered. Add `local answer` as the first line of the function. – chepner Jul 13 '20 at 17:09