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
[ "$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!
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!
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
_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 ''
![]() | |
!! |
+ empty_test val1= val2= + _empty_test + [ ] + echo $1 is empty $1 is empty + echo == minus, \n
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