Home > Back-end >  Access value of read input from within a function in Bash
Access value of read input from within a function in Bash

Time:01-07

I'm have a function wrapper for read command. I'm trying to automate most of input asking in my script by a function. Below is non-working code.

ask_input() {
  _question="$1"
  _thevar="$2"
  _finalvar=$(eval $(echo $_thevar))
  read -ep "${_question}: " "$_thevar"
  printf "%s\n" "$_question" "$_thevar" "$_finalvar"
}

Basically what I'm hoping is when I execute following.

ask_input "Do you like apple (yes/no)" the_answer

If an user type yes, each variable will contain following (w/o quotes of course, it was just for easier readability).

$_question --> "Do you like apple (yes/no)"
$_thevar --> "the_answer"
$_finalvar --> "yes"

The eval command is my attempt to solve the problem, but I have not found the actual solution to this.

CodePudding user response:

The main two things you need to change are: 1) use indirect expansion with ! (_finalvar="${!_thevar}") instead of messing with eval, and do that after reading something into that variable. I'd also recommend making all those variables local to the function. So something like this:

ask_input() {
    local _question="$1"
    local _thevar="$2"
    read -ep "${_question}: " "$_thevar"
    local _finalvar="${!_thevar}" 
    printf "%s\n" "$_question" "$_thevar" "$_finalvar"
}

Since those variables are local now, you could probably also remove the _ prefixes (unless you're worried about a conflict with the variable name supplied as $2).

  • Related