testing empty 

Synopsis 

b=''
b=T
[ "$b" ] && echo b is not empty!       # way to test empty!
[ "$b" ] || echo b is empty!           # way to test not empty!
if [ "$b" ] ; then echo b is true! ; else echo b is false; fi

Usage 

[ "$b" ] || echo b is empty!           # lazy way to test not empty!
[ -z "$b" ] && echo b is empty.        # formal way to test empty!
[ ! -z "$b" ] && echo b is not empty.  # formal way to test empty!

Trying History 

b=''
if [ "$b" ] ; then echo b is true! ; fi
if [ ! "$b" ] ; then echo b is false! ; fi

yield:

+ [  ]
+ [ ! ]
/home/users/suntong/bin/sh.test.script: test: argument expected

Right way:

[ "$b" ] && echo b is not empty!       # way to test empty!
[ "$b" ] || echo b is empty!           # way to test not empty!

test empty and something else 

Symptom 

this will not work:

printf "Writing to " >&2
  # for "txt" command with no 'saved_name' parameter provided,
  # write to stdout instead of saving to file
if [ "$1" ] || [ $sfunc = txt ] ; then
  printf "standard output" >&2
  save_to=
else
  save_to=T                   # will save
fi
+ printf Writing to
Writing to + [ aaaa ]
+ printf standard output

Conclusion / Solution 

use [ -z ] !

more on empty test: 

_empty_test(){

if [ "$1" ]; then
  echo "\$1=$1";
else
  echo "\$1 is empty";
fi

echo "== ${1-minus}, ${1+plus}\n"

}

empty_test(){
  val1=$1;
  val2=${1+"$@"};

  _empty_test $val2 ; _empty_test "$val2" ;     # different!
}

calls: call empty_test with ''

[Tip]

!!

+ empty_test
val1=
val2=
+ _empty_test
+ [  ]
+ echo $1 is empty
$1 is empty
+ echo == minus, \n

minus, 

+ _empty_test
+ [  ]
+ echo $1 is empty
$1 is empty
+ echo == , plus\n

Conclusion 

[ ] will always tells you that string is empty

but ${+} and ${-} can tell the difference!

more on parameter passing 

empty_test 'a' 'b'
+ empty_test a b
val1=a
val2=a b
+ _empty_test a b
+ [ a ]
+ echo $1=a
$1=a
+ echo == a, plus\n

a, plus 

+ _empty_test a b
+ [ a b ]
+ echo $1=a b
$1=a b
+ echo == a b, plus\n
[Tip]

!!

so we can see passing $val2 or "$val2" is different

documented on: 1999.12.06 Mon 12:02:39