Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash indirect variable assignment inside a function

I have a script where the user input needs to be evaluated several times, the solution im working on is to put the evaluation bits into a function, and simply call the function every time i need to evaluate the input. The problem is though that when im trying to update the $1 variable (that referes to the first variable parameter of the function) I get the error message "$VARIABLE command not found".

Here is the code:

function input_handler() {
 if is_integer $1; then
  selid="$1 -1"
  if [[ "$1" -le "0" ]]; then
   echo "Please use a simple positive number!"
  else
   if [[ "$1" -le "${#array[*]}" ]]; then
    eval $1="${array[selid]}"
    echo "Ok, moving on..."
   else
    echo "That number seems too large, try again?"
   fi
  fi
 else
  if [ -e $2/$1 ]; then
   echo "Ok, moving on..."
  else
   echo "That item is not on the list, try again!"
  fi
 fi
}

And this command:

input_handler $doctype $docpath

Gives this output:

5
./test: line 38: 5=sun: command not found

Ok, moving on...

Now this is almost correct, but what im after is doctype=sun, not 5=sun, in other words I need the $1 variable name not its value. Changing the line eval $1="${array[selid]}" to eval doctype="${array[selid]}" fixes this particular instance. But this does not fix my problem as I need to run this function on different variables with different names.

like image 715
Dan-Simon Myrland Avatar asked Oct 21 '22 11:10

Dan-Simon Myrland


1 Answers

Maybe not fully understand what you want achieve, but check the next example:

weirdfunc () {
    echo " weirdfunc: variable name is: $1"
    echo " weirdfunc: variable value is: ${!1}"
    eval "$1=$(( ${!1} + 1))" #assign
}

myvar="5"
echo "the value of myvar before: $myvar"

weirdfunc myvar #call with the NAME not with the value, so NOT weridfunc $myvar

echo "the value of myvar after: $myvar"

In short - when you want to do anything with the variable NAME in an called function, you should pass the NAME of the variable and NOT his value. So call the function

somefunc NAME

instead of

somefunc $NAME

and use the above constructs to get the name and value inside the function.

like image 145
jm666 Avatar answered Oct 29 '22 21:10

jm666