问题
In my bash test
has an attitude to exit with status 0
:
$ test -n && echo true || echo false
-> true
while
$ test -n "" && echo true || echo false
-> false
It means when it doesn't receive any argument at all, it assumes nonzero.
The case -z
works properly instead:
$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true
Is this the expected behavior?
回答1:
Basically, you are asking test whether the string "-z" is nonempty. It is, so it tells you true
. The actual algorithm test uses is:
0 arguments:
Exit false (1).
1 argument:
Exit true (0) if $1 is not null; otherwise, exit false.
2 arguments:
If $1 is '!', exit true if $2 is null, false if $2 is not null.
If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.
Otherwise, produce unspecified results.
...
Quoted from the POSIX test command specification.
回答2:
Presumably, without arguments "-n" and "-z" are not treated as operators but as mere strings, and test "a non-empty string"
is true. I would guess that test
counts its arguments as a first step, and if the count is 1, simply examine the length of the argument.
回答3:
Yes it is expected.
$ man test
-n string True if the length of string is
non-zero.
-z string True if the length of string
string is zero.
test [option] #without any operand
returns an exit status that is true for ALL options.
Try these:
test -d
test -f
test -n
test -G
test -k
...
来源:https://stackoverflow.com/questions/7890017/bash-test-behaves-unconformly