noober noober - 2 years ago 170
Bash Question

bash - expanding a string containing environment variable references

I'm using a

shell. I have some values from my
that I want to extract and assign those values to a variable. I also need to split it at the
sign. What's the best utility for this using bash?

I basically need to create a string with these values stripping out the delimter as well:

echo -e "This is my $KEY and my profile is $PROFILE"
This is my Ru2cXJbgWQ0wdtKBGbS5/nVQvGo and my profile is foobar


-bash-4.1$ echo -e "This is my $KEY"
This is my
-bash-4.1$ env | grep KEY


$ env | grep KEY

$ env | grep DEFAULT_PROFILE

Answer Source

To complement Anthony Geoghegan's helpful answer, which shows that Bash automatically represents environment variables as shell variables[1]:

In short: the fact that env | grep KEY returns KEY=Ru2cXJbgWQ0wdtKBGbS5/nVQvGo does NOT necessarily mean that an environment variable named KEY exists.

It is conceivable that the grep matches you're getting are matches of other environment variables' values or even the last line of multi-line variable name. Thanks, chepner.

While environment variable and values are typically single-line, they don't have to be. An example is Bash's own ability to export functions, whose typically multi-line definitions are exported as the values of specially named environment variables.

To verify that a given (Bash) shell variable is indeed based on an environment variable, use:

declare -p KEY  # example with variable name 'KEY'

If KEY is indeed an environment variable, you'll see (using your example):

declare -x KEY="Ru2cXJbgWQ0wdtKBGbS5/nVQvGo"

Note the -x, which indicates an exported variable, which is synonymous with being an environment variable.

By contrast:

  • If KEY is a shell variable that isn't also an environment variable, the -x will be missing.

  • if KEY is neither a shell variable nor an environment variable, you'll see an error message.

anubhava, in a comment on the question, demonstrates a shell-independent way to test if an environment variable is defined:

printenv KEY  # prints value of env. var. 'KEY'

An exit code of 0 tells you that the variable exists (even if it is has no value).

Note that printenv is an external utility that is not POSIX-compliant; it does, however, come with both Linux and BSD/OSX.

[1] Note that by using Bash's own string expansion (interpolation of double-quoted strings), what gets expanded is not only environment variable references, but also shell-only variable references. GNU utility envsubst, by contrast, allows you to restrict expansion to environment variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download