【问题标题】:test command: difference between -n and -z测试命令:-n 和 -z 的区别
【发布时间】:2014-04-22 18:36:52
【问题描述】:

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

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

这是一个错误吗?

【问题讨论】:

    标签: fish


    【解决方案1】:

    这不是错误!

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

    好旧的 IEEE 1003.1 tells us what test must do in this case:

    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 始终成为一个参数(可能为空)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 2020-08-07
    • 2017-09-18
    • 2016-09-29
    • 2018-11-26
    相关资源
    最近更新 更多