Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
share|improve this question
    
Check The Advanced Bash-Scripting Guide: tldp.org/LDP/abs/html/ivr.html –  Andrew Nov 20 '11 at 6:30
add comment

3 Answers

up vote 3 down vote accepted

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
share|improve this answer
add comment

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
}
share|improve this answer
    
Thanks, i guess read gets around the use of eval –  engineerchuan Nov 19 '11 at 21:45
add comment
#!/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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.