string check in bash with -z and -n -


i made mistake in test syntax in bash want understand happens in string check -n , -z. wrote following lines in linenum variable line number grep. when string not found (there 1 in file, sure), linenum variable empty.

$ linenum=$(grep -w -n mystring myfile | cut -d: -f1) $ echo --$linenum-- ---- $ if [ -n $linenum ] ; echo "checked -n"; fi checked -n $ if [ -z $linenum ] ; echo "checked -z"; fi checked -z 

then realized forgot double quotes , following check gave me:

$ if [ -n "$linenum" ] ; echo "checked -n"; fi $ if [ -z "$linenum" ] ; echo "checked -z"; fi checked -z 

so, in former tests, forgot double quotes, versus did if test check , really, since got 2 positive checks both -n , -z ?

without quotes, test statement (with either operator, represented -x here), reduces to

if [ -x ]; echo "checked -x"; fi 

according posix standard, one-argument form of test (which have here) true if argument non-null. since literal string -x non-null (it's not operator anymore), evaluates true.

with quotes, get

if [ -x "" ]; echo "checked -x"; fi 

since quotes force empty 2nd argument, have 2-argument form of test, , -x (whether -n or -z) recognized primary operator acting on 2nd, null, argument.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -