Q:

Bash Functions - Create a variable with parameter's label

I'm trying to create a function which will create a variable with the tag $1 (first param) and with the value $3 (third param).
Here is my code:
function var
{
    if [ "$2" = "=" ]; then
        $1 = $3
    fi
}

Now, I believe the reason this doesn't work is because the way I wrote this function makes bash try to overwrite the value of $1 with that of $3.
Is there a work-around for this?
This is what I'm aiming to do:
var i = 1
var greeting = "hello"

and both of these variables would be assigned their value.

A:

Don't use eval, use declare with the -g flag (create global variables)
function var {
    if [ "$2" = "=" ]; then
        declare -g "$1=$3"
    fi
}
var foo = bar
echo $foo

bar

