2

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.

1 Answer 1

3

$$ 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).

Sign up to request clarification or add additional context in comments.

2 Comments

Took me forever to find this reply! Thank you for making this answer 3 years ago.
Glad it helped! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.