Bash assignment of an indirect variable inside a function

I have a script where user input needs to be evaluated several times, im solution is to put evaluation bits in the function and just call the function every time I need to evaluate the input. The problem is that when I try to update a variable $1(which refers to the first variable parameter of the function), I get the error "$ 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 conclusion:

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

Ok, moving on ...

, im is doctype = sun, 5 = sun, , $1 . eval $1="${array[selid]}" eval doctype="${array[selid]}" . , .

+5
4

, , , :

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"

, - NAME , .

somefunc NAME

somefunc $NAME

, .

+4

$1 , set.

$ f() { echo "$@"; set -- a b c; echo "$@"; echo $2; }
$ f 1 2 3
1 2 3
a b c
b

, , , $2, .

, , .

0

, Bash $1 $1 = .

eval "$1"=${array[selid]}
0

. , . -

foo=$1

$foo $1

-1

All Articles