用-z和-n在bash中进行字符串检查 [英] string check in bash with -z and -n

查看:104
本文介绍了用-z和-n在bash中进行字符串检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash中的测试语法中犯了一个错误,但现在我想了解使用 -n -z
我写了以下几行以从 grep 的行中获取 LINENUM 变量。如果找不到该字符串(肯定在文件中只有一个),则 LINENUM 变量为空。

I made a mistake in test syntax in bash but now I want to understand what really happens in string check with -n and -z. I wrote the following lines to get in LINENUM variable the line number from a grep. When the string is not found (there is only one in the file, for sure), the LINENUM variable is empty.

$ LINENUM=$(grep -w -n mystring myfile | cut -d: -f1)
$ echo --$LINENUM--
----
$ if [ -n $LINENUM ] ; then echo "Checked -n"; fi
Checked -n
$ if [ -z $LINENUM ] ; then echo "Checked -z"; fi
Checked -z

然后我意识到我忘记了双引号,然后进行了以下检查给我:

Then I realized I forgot the double quotes and then the following check gave to me:

$ if [ -n "$LINENUM" ] ; then echo "Checked -n"; fi
$ if [ -z "$LINENUM" ] ; then echo "Checked -z"; fi
Checked -z

因此,在以前的测试中,我忘记了双引号,而不是进行if测试检查,实际上是因为我从 -n -z 获得了两次肯定的检查?

So, in the former tests, where I forgot the double quotes, versus what did the if test check , really, since I got two positive checks from both -n and -z ?

推荐答案

没有引号的情况下,您的测试语句(使用任一运算符,均用 -X ),如果[-X],则减少为

Without the quotes, your test statement (with either operator, represented with -X here), reduces to

if [ -X ]; then echo "Checked -X"; fi

根据POSIX标准, test <如果参数为非null,则/ code>(现在在此处具有)为true。由于文字字符串 -X 不为空(不再是运算符),因此其计算结果为true。

According to the POSIX standard, the one-argument form of test (which you now have here) is true if the argument is non-null. Since the literal string -X is non-null (it's not an operator anymore), it evaluates to true.

使用引号,如果[-X],您将获得

With the quotes, you get

if [ -X "" ]; then echo "Checked -X"; fi

由于引号强制为空的第二个参数,因此您使用的是2个参数形式的 test -X -n -z )被正确识别为对第二个null参数起作用的主要运算符。

Since the quotes force an empty 2nd argument, you have a 2-argument form of test, and -X (whether -n or -z) is properly recognized as a primary operator acting on the 2nd, null, argument.

这篇关于用-z和-n在bash中进行字符串检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆