-1

What is the standard way, in bash, to check if an environment variable is set up? I'm a little confused between the following options:

  1. ! [ -z "${VAR}" ]
  2. [ -n "${VAR}" ]
  3. [ "${VAR}" ]

Or is there a better approach?

4
  • 1
    "sota"? All of those do the same thing, namely checking if the shell variable VAR is set to any non-empty value. Regardless of it was received from the shell's environment or marked for exporting to the environment of any programs the shell starts.
    – ilkkachu
    Commented Apr 14 at 11:53
  • None of the given lines of code verifies that the given variable is an environment variable. Is that something that you need to do too?
    – Kusalananda
    Commented Apr 14 at 11:56
  • @ilkkachu I mean state of the art :). They do the same things but which one is considered as the "standard" or most common used? What is the best practice here
    – kj-crypto
    Commented Apr 14 at 11:57
  • 2
    Your question seems to be similar to asking whether one should say “is not empty” or “is non-empty”. I think it comes down to personal preference. I would avoid then last variant though as it looks like you’ve accidentally left out the test operator (I know it works, it just looks sloppy).
    – Kusalananda
    Commented Apr 14 at 11:59

2 Answers 2

2

-n checks if a variable is not null.

In bash 4.2 or later you have the -v operator which checks if a variable is set even if it doesn't have a value, so that might be a scenario you want to cover.

Bash uses the extended test [[ so the "bash" test would be:

[[ -n "$VAR" ]]

However this variable could just be a local variable, if you want to check if it's exported you would need something like:

if env | grep -q '^VAR='; then
4
  • 3
    env | grep -q '^VAR=' could give false positives if there are environment variables whose values contain \nVAR=. Commented Apr 14 at 13:11
  • 2
    Note that having an empty value (like after VAR=) is not the same as having no value (like after unset -v VAR; export VAR or VAR=()). Commented Apr 14 at 13:13
  • declare -x should show them all.
    – Jetchisel
    Commented Apr 14 at 15:23
  • 1
    Maybe worth a mention that if testing a variable (e.g. VAR) against -v, the variable name must not be expanded; i.e. if [[ ! -v VAR ]]; then echo "unset"; fi instead of if [[ ! -v $VAR ]]; then echo "unset"; fi. REF
    – Seamus
    Commented Apr 15 at 7:40
1

Try this:

if [[ ! -v VAR ]]; then 
   echo "unset"
fi

NOTE: Do not expand VAR; use VAR - not $VAR

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.