Search code examples
bashshdash-shell

Portable way to check emptyness of a shell variable


What is the portable and canonical way to test if variable is empty/undefined in a shell script? It should work in all sh-like shells. What I do now is something like:

if [ -z "$var" ] ; then
    ...

and for reverse, doing something when variable is not empty/undefined:

if [ -n "$var" ] ; then
    ...

And while these work for the scripts I write now, I'd like to know a way, that will work in any reasonably compatible sh-like shell, even on some more obscure environment than a Linux PC with GNU userland and bash or dash.

I'm looking for an "expert answer" from someone who is experienced in different shell environments and knows the pitfalls of different ways of doing things, not an opinion like "that should work".


Solution

  • Disclaimer: I don't consider myself an expert in shells.

    AFAIK, the test command and the -z and -n flags are part of the POSIX standard, so you should be fine by using them across many platforms.