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
Best Answer
From
man bash
So