-1

using /bin/sh how to check if environment variable is set.

The below command works for /bin/bash but not for /bin/sh

if [[ -v PROXY_PASS_MAPPING ]]; then echo "set" fi

what command will work for /bin/sh

kumar
  • 8,207
  • 20
  • 85
  • 176
  • 1
    Doesn't https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash answer your question? – KamilCuk Oct 25 '22 at 10:37
  • @KamilCuk : The question which you are linking to, deals about how to test for a **variable** to be defined, while the OP wants to know whether a variable is in the **environment**. Admittedly, this point is missing in the OP's bash solution as well. – user1934428 Oct 25 '22 at 11:26
  • @kumar: Even in bash, you don't test for **environment** variables, but just for **variables** to be set. For verifying the environment in bash **and** POSIX shell, use `printenv`. – user1934428 Oct 25 '22 at 11:28

1 Answers1

0

This solution should work for POSIX shell and bash:

if [ -n "$(printenv PROXY_PASS_MAPPING)" ]
then 
  echo The Variable is not empty and in the environment
fi

This does not catch the case where the variable is in the environment and empty. To test this, you can use

if printenv PROXY_PASS_MAPPING >/dev/null
then
  echo The Variable is in the environment
else
  echo The variable is not in the environment
fi
user1934428
  • 19,864
  • 7
  • 42
  • 87