ealeon
ealeon

Reputation: 12462

bash: if block fo if env var is not empty

In the below example, else block is for if env var is not empty. i would like for it to go to if then block

if [ -z "$var" ]
then
      echo "\$var is empty"
else
      echo "\$var is NOT empty"
fi

would it be negating the if block?

if ! [ -z "$var" ]
then
      echo "\$var is empty"

Upvotes: 0

Views: 136

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 185560

Yes, you can invert like this :

if ! [ -z "$var" ]

or

if [ ! -z "$var" ]

or even better using bash test :

if ! [[ -z $var ]]

or

if [[ -n $var ]]

or even simply

if [[ ! $var ]]

[[ is a bash keyword similar to (but more powerful than) the [ command. See http://mywiki.wooledge.org/BashFAQ/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals. Unless you're writing for POSIX sh, we recommend [[.

Upvotes: 1

Related Questions