Testing For Null Or Empty String In Bash Versus Powershell

Pavol Kutaj
2 min readOct 28, 2021

--

The aim of this pageđź“ť is to show the use of [-n "$foo"] and [-z "$foo"] comparison operators in bash. I am learning how to read bash and I have encountered.

if [ -z "${env_json}" ]; then

Which executes only if ${env_json} evaluates to an empty string. I am also adding pieces from Powershell (posh) and python (it's PEP8 style guide).

1. bash

  • there is no built-in null variable
  • there is a built-in null command, but that is a different story
  • Comparison Operators
-n
string is not null.

-z
string is null, that is, has zero length
  • To illustrate with an AND logical operator (&&) where the statement executes only if both of the clauses evaluate to true
$ foo="bar";
$ [ -n "$foo" ] && echo "foo is not null" #true > echo executes
foo is not null
$ [ -z "$foo" ] && echo "foo is null" #false > nothing
$ foo="";
$ [ -n "$foo" ] && echo "foo is not null" #false > nothing
$ [ -z "$foo" ] && echo "foo is null" #true > echo executes
foo is null

2. posh and pep8

  • the empty string evaluates to False in a test
  • but it is not $null
if ($foo) {echo "hello there"}  # false
if ($null -eq $foo) {echo "hello there"} # false
if (-not $foo) {echo "hello there"} # true
>>> hello there
  • there are other methods in posh but I would side with Python’s PEP8 (Style Guide) that the above is the best way

For sequences, (strings, lists, tuples), use the fact that empty sequences are false

— PEP8

3. links

--

--

No responses yet