linux - BASH:[](测试)行为不一致

标签 linux bash gnu

在我的 bash 中 test 有退出状态 0 的态度:

$ test -n && echo true || echo false
-> true

同时

$ test -n "" && echo true || echo false
-> false

这意味着当它根本没有收到任何参数时,它假定为非零值。

情况 -z 可以正常工作:

$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true

这是预期的行为吗?

最佳答案

基本上,您是在询问测试字符串“-z”是否为非空。它是,所以它告诉您 true。实际算法测试使用的是:

  • 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.

...

引自the POSIX test command specification .

关于linux - BASH:[](测试)行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7890017/

相关文章:

python - 如何设置带有评估集的学习xgboost?

r - 在 R 中为 system() 设置环境变量?

c - POSIX 系统上 regex.h header 的不同实现背后的算法类型

linux - Subversion 提交在第一个文件后无限期挂起

linux - 仅从 Linux MQSeries 客户端获取 JmqiException RC=2538;AMQ9204

bash - awk:如何从文件 A 中提取文件 B 中指定索引的列?

C - 解压缩 Gzipped http 响应

linux - GNU find -exec 命令 {} ; vs -exec 命令 {} +

linux - 两个优先级相同的SCHED_FIFO任务在Linux中是否在每个周期内获得处理时间?

linux - 在日志文件中搜索特定文本,然后将日志文件的所有内容合并到一个文件中