0

In bash, I know that there are a few ways to check whether a given variable is defined and contains a value. However, I want to check whether a given variable exists in the environment, and not as simply a local variable. For example ...

VAR1=value1 # local variable
export VAR2=value2 # environment variable
if [[ some_sort_of_test_for_env_var VAR1 ]]
then
  echo VAR1 is in the environment
else
  echo VAR1 is not in the environment
fi
if [[ some_sort_of_test_for_env_var VAR2 ]]
then
  echo VAR2 is in the environment
else
  echo VAR2 is not in the environment
fi

How can some_sort_of_test_for_env_var be defined so that the bash code above will cause the following two lines to be printed?

VAR1 is not in the environment 
VAR2 is in the environment

I know that I can define a shell function to run env and do a grep for the variable name, but I'm wondering if there is a more direct "bash-like" way to determine whether a given variable is in the environment and not just a local variable.

Thank you in advance.

2 Answers 2

6

Your title and body are very different.

Your title is either impossible or meaningless. All environment variables in bash are also shell variables, so no environment variable ever can be 'only' in the environment.

For your body

if declare -p VARNAME | grep -q '^declare .x'; then # it's in the environment
# or typeset if you prefer the older name

If you particularly want the [[ syntax

if [[ $(declare -p VARNAME) == declare\ ?x* ]] # ditto
3
  • Yes, good point about all environment variables also being shell variables. I'll fix the title of the post. And thank you for pointing out that declare -p is the answer! Actually, I now see that all I need to do is check the return code from declare -p VAR: e.g., declare -p VAR 1>/dev/null 2>&1 && echo VAR is in the environment.
    – HippoMan
    May 13 at 2:51
  • @HippoMan That would match unexported variables too (so plain shell variables and not just environment variables). You need to check if it has the x flag like this answer does for environment variables.
    – muru
    May 13 at 2:58
  • Oh ... you're right. I see. In any case, declare -p is the answer. Thanks to both of you!
    – HippoMan
    May 13 at 2:59
2

You could spawn a new shell and inquire if the variable exists:

$ bash -c '[[ -v VAR2 ]]' && echo variable is exported || echo variable is not exported
variable is exported

$ bash -c '[[ -v VAR1 ]]' && echo variable is exported || echo variable is not exported
variable is not exported

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.