2

I would like to write a bash function where i provide a string and it assigns the value "hi" to a variable with that string's name. I'm sure this has been answered before but I don't know the keyword to lookup in manual.

myfunc() {
  ## some magic with $1
  ## please help me fill in here.
}

myfunc "myvar"
echo $myvar
> hi

After answer. Thanks guys. I wrote a function to look for an environment variable and prompt for it if its not there. Would appreciate any improvements. I believe it works.

get_if_empty() {
    varname=$1
    eval test -z $`echo ${varname}`;
    retcode=$?
    if [ "0" = "$retcode" ]
    then
        eval echo -n "${varname} value: "
        read `echo $1` # get the variable name
    fi
    eval echo "$1 = $`echo ${varname}`"

}

Here is the usage:

get_if_empty MYVAR
1

3 Answers 3

3

From man bash

   eval [arg ...]
          The  args are read and concatenated together into a single command.  This command is then read and executed by the shell, and its exit status is returned as the value of
          eval.  If there are no args, or only null arguments, eval returns 0

So

myfunc() {
    varname=$1
    eval ${varname}="hi"
}

myfunc "myvar"
echo $myvar
1

Your get_if_empty function is way more complicated than it needs to be. Here's a much simplified version:

get_if_empty() {
    if [ -z "${!1}" ]; then   # ${!var} is an "indirect" variable reference.
        read -p "$1 value: " $1
    fi
}
0
0
#!/bin/bash
indirect() {
    [[ "$1" == "get" ]] && {
        local temp="$2"
        echo ${!temp}
    }
    [[ "$1" == "set" ]] && read -r $2 <<< "$3"
}

indirect set myvar Hi
echo $myvar

Hi=$(indirect get myvar)
indirect get Hi

double=$(indirect get $Hi)
indirect get $double

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .