noober noober - 7 months ago 35
Bash Question

bash - parsing a name value pair with delimiter from env

I'm using a

bash
shell. I have some values from my
env
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


Result:

-bash-4.1$ echo -e "This is my $KEY"
This is my
-bash-4.1$ env | grep KEY
KEY=Ru2cXJbgWQ0wdtKBGbS5/nVQvGo


Example:

$ env | grep KEY
KEY=Ru2cXJbgWQ0wdtKBGbS5/nVQvGo

$ env | grep DEFAULT_PROFILE
DEFAULT_PROFILE=foobar

Answer

To complement Anthony Geoghegan's helpful answer:

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.