Brian Brown
Brian Brown

Reputation: 4311

Bash function, export function argument as environment variable

I wrote a bash function to export an environment variable. First function argument is a variable name, second is a variable value. I want to echo it to show what value was exported:

#!/bin/bash

env_var_export()
{
    export $1=$2

echo ""
echo "  export $1=$$1"
echo ""
}

env_var_export var defaultVal456

I mean, echo should print: export var=defaultVal456. Any help? I know I can do this:

echo ""
echo "  export $1=$2"
echo ""

but its not the solution to my problem.

Upvotes: 2

Views: 2129

Answers (1)

FatalError
FatalError

Reputation: 54611

$$ is a special variable that expands to the shell's pid, and that's what is going to be evaluated in your echo. You should instead use an indirect reference like this:

echo ""
echo "  export $1=${!1}"
echo ""

This syntax will take the variable named in $1 and then lookup the value based on that name (i.e. indirection).

Upvotes: 3

Related Questions