unix 中的测试命令不打印输出

ind*_*man 23 shell bash command test

当我在终端输入这个

test 4 -lt 6
Run Code Online (Sandbox Code Playgroud)

我没有得到任何输出。为什么不?我需要那个 0 或 1

man*_*ork 18

你得到 0 或 1。在退出代码中。

bash-4.2$ test 4 -lt 6

bash-4.2$ echo $?
0

bash-4.2$ test 4 -gt 6

bash-4.2$ echo $?
1
Run Code Online (Sandbox Code Playgroud)

更新:要存储退出代码供以后使用,只需将其分配给一个变量:

bash-4.2$ test 4 -lt 6

bash-4.2$ first=$?

bash-4.2$ test 4 -gt 6

bash-4.2$ second=$?

bash-4.2$ echo "first test gave $first and the second $second"
first test gave 0 and the second 1
Run Code Online (Sandbox Code Playgroud)

  • 不可以。只能重定向输出。无论如何,通常没有必要这样做。要将其存储以备后用,只需将其分配给一个变量即可。或者告诉我们您对该值的确切意图是什么。 (4认同)
  • 有没有办法管道退出代码? (2认同)
  • 退出代码被放置在 `$?` 变量中——至少直到它被你执行的下一个命令覆盖。 (2认同)

rus*_*ush 8

另一种方式是

test 4 -lt 6 && echo 1 || echo 0
Run Code Online (Sandbox Code Playgroud)

但在这种情况下要小心。如果test返回成功和echo 1失败echo 0将被执行。