gpt4 book ai didi

Bash 操作符 : "!" vs "-z"

转载 作者:行者123 更新时间:2023-12-04 02:58:36 26 4
gpt4 key购买 nike

运算符“!”有什么区别?和“-z”应用于字符串?

#Example 1
if [ ! STRING ]; then ...

#Example 2
if [ -z STRING ]; then ...

谢谢

最佳答案

首先,您使用单个括号。这意味着您使用的是 test 命令而不是 Bash 内置函数。从手册:

test EXPRESSION or [ EXPRESSION ]: this exits with the status returned by EXPRESSION

! EXPRESSION: test returns true of EXPRESSION is false

-z STRING: test returns true if the length of STRING is zero.


例子:
$ [ -z "foo" ] && echo "zero length" || echo "non-zero length"
non-zero length
$ [ ! -z "foo" ] && echo "non-zero length" || echo "zero length"
non-zero length
$ [ -z "" ] && echo "zero length" || echo "non-zero length"
zero length
$ [ ! -z "" ] && echo "non-zero length" || echo "zero length"
zero length
但是现在您想知道 [ ! STRING ] :
手册指出 [ STRING ] 等效于 [ -n STRING ] ,它测试 STRING 是否具有非零长度。因此 [ ! STRING ] 等价于 [ -z STRING ]

-n STRING: the length of STRING is nonzero.

STRING: equivalent to -n STRING

source: man test



答案: [ ! STRING ] 等价于 [ -z STRING ]

关于Bash 操作符 : "!" vs "-z",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com