Why bash -n and -z operators do not invert for $ @

function wtf() {
  echo "\$*='$*'"
  echo "\$@='$@'"
  echo "\$@='"$@"'"
  echo "\$@='""$@""'"
  if [ -n "$*" ]; then echo " [ -n \$* ]"; else echo "![ -n \$* ]"; fi
  if [ -z "$*" ]; then echo " [ -z \$* ]"; else echo "![ -z \$* ]"; fi
  if [ -n "$@" ]; then echo " [ -n \$@ ]"; else echo "![ -n \$@ ]"; fi
  if [ -z "$@" ]; then echo " [ -z \$@ ]"; else echo "![ -z \$@ ]"; fi
}

wtf

produces

$*=''
$@=''
$@=''
$@=''
![ -n $* ]
 [ -z $* ]
 [ -n $@ ]
 [ -z $@ ]

although it seems to me that it [-n $@]should be false, because 7.3 Other comparison operators indicate that it [ -n "$X" ]should be the opposite of [ -z "$X" ]for all $X.

-z

string is null, i.e. has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

-n

Line

not equal to null.

The test -nrequires the string to be enclosed in test brackets. However, using an unquoted string with ! -zor even just an incorrect string in test brackets (see Example 7-6) usually works, but this is an unsafe practice. Always specify a verified string. [1]

, $@ , , , . ?


$ bash -version | head -1
GNU bash, version 4.2.42(2)-release (i386-apple-darwin12.2.0)

- 1 0

$ [ -n "$@" ]; echo "$?"
0
+5
2

$@ , "$@" ; . ,

[ -n "" ]

[ -n ]

-n , , .

+7

"$@" , . "$*", , script.

, . a b c, "a" "b c" (.. ), "$*" "a b c", $* a b c ( ).

+1

All Articles