3

鉴于此驱动程序功能仅在给定特定输入的情况下产生输出:

function driver -a arg
  test $arg = 1; and echo OK
  return 0
end

当函数发出输出时,一切正常:

$ driver 1 | od -c
0000000   O   K  \n
0000003
$ test -z (driver 1); and echo no output; or echo some output
some output
$ test -n (driver 1); and echo some output; or echo no output
some output

但在没有输出的情况下:

$ driver 0 | od -c
0000000
$ test -z (driver 0); and echo no output; or echo some output
no output
$ test -n (driver 0); and echo some output; or echo no output
some output

这是一个错误吗?

4

1 回答 1

7

这不是一个错误!

命令替换(driver X)执行驱动程序函数,然后将每个输出行转换为参数。在 (driver 0) 的情况下,没有输出,因此您得到零参数。所以无输出情况等价于运行test -zand test -n

良好的旧 IEEE 1003.1告诉我们在这种情况下必须执行什么测试

1 个参数:如果 $1 不为空,则退出 true(0);否则,退出 false

因此,当 -n 是唯一的参数时,它会失去其作为标志的状态,并且您最终会测试 '-n' 的非空性(当然它通过了)。

您可以在 bash 中看到相同的行为:

> test -n `echo -n` ; echo $?
0

在fish中,如果要检查字符串是否为非空,可以使用count

if count (driver 0) > /dev/null
    # output!
end

您还可以在测试中使用中间变量:

set -l tmp (driver 0)
test -n "$tmp" ; and echo some output; or echo no output

引号确保 $tmp 始终成为一个参数(可能为空)。

于 2014-04-23T02:02:43.597 回答