How to test validity of an environment variable with bash checking if it exists and is is true?

Solution 1:

Such a test does not exist as it might in a high-level language such as Java or C#, but it is relatively easy to construct.

Three comments on your question as asked:

1: You do not work with literal "true"/"false" values in bash; all commands and conditional constructs yield an exit status, or logical result, which is either 0 (true) or non-0 (false).
Work with this, don't try to re-invent the wheel.

2: Try not to use upper-case parameter names unless they are environment variables; this is a simple convention that helps keep your code clean.

3: What, exactly, do you mean by "NULL"? The literal string NULL, an empty value, or something else?
The latter two concepts don't exist in bash; a NULL variable would be unset, which you're already checking for.

The most effective solution would be a function that accepts a variable (or parameter, as bash calls them), and checks for those conditions, then sets the exit status based on that, effectively condensing multiple truth values to a literal 0 or 1.

For example:

is_true() { if [[ "$1" = 0 ]]; then false; elif [[ -z "$1" ]]; then false; elif [[ "$1" =~ [Ff][Aa][Ll][Ss][Ee] ]]; then false; fi; }

  • is_true "1" yields 0, which is true
  • is_true "false" yields 1, which is false
  • a=10; is_true "$a" yields 0
  • grep -q something somefile yields 0 if something appears at least once in somefile.

NOTE that the latter example clearly shows that you don't NEED such a construct; everything that happens in bash already works with these basic 0/1 truth values.

But I'll grant that you might have to convert input from some gnarly external program :)

Solution 2:

I find these comparisons unuseful because they make appearance of code obscur and unobvious. I just use the nice feature of bash, that comes since v4.2, from the manpage:

   -v varname
          True if the shell variable varname is set (has been assigned a value).

Usage is very simple

OUTPUT_TO_LOG=1
if [ -v OUTPUT_TO_LOG ]; then
    exec > &>./logfile
    …
fi

In other words, to flag as enabled, just define. Try it!

$ :() { if [ -v VAR ]; then echo 'existed'; fi }
$ unset VAR && :          # no output
$ unset VAR && VAR= && :  # "existed"
$ unset VAR && VAR=1 && : # "existed"