Shell 脚本:-z 和 -n 选项与 if

use*_*953 113 shell-script

我有一个 shell 脚本,其中有以下几行if [ -z "$xyz" ]if [ -n "$abc" ],但我不确定它们的目的是什么。谁能解释一下?

ter*_*don 138

您可以在此处找到有关 bash 运算符的非常好的参考资料。如果您使用不同的外壳,只需搜索即可<my shell> operators找到所需的一切。在您的特定情况下,您正在使用:

-n
   string is not null.

-z
  string is null, that is, has zero length
Run Code Online (Sandbox Code Playgroud)

为了显示:

$ foo="bar";
$ [ -n "$foo" ] && echo "foo is not null"
foo is not null
$ [ -z "$foo" ] && echo "foo is null"
$ foo="";
$ [ -n "$foo" ] && echo "foo is not null"
$ [ -z "$foo" ] && echo "foo is null"
foo is null
Run Code Online (Sandbox Code Playgroud)

  • 如果您在使用 `-n` 时遇到问题,可能是因为您遵循了网络上的一些糟糕指南(例如 [GeeksforGeeks](https://www.geeksforgeeks.org/string-operators-shell-script /) 或 [TutorialsPoint](https://www.tutorialspoint.com/unix/unix-string-operators.htm)) 不引用变量。这个答案,以及这里链接的指南,正确引用它。**如果你使用 `-n` 而不加引号,它会告诉你它不是空的,即使它是空的!** @terdon,非常感谢! (3认同)

小智 7

为了扩展terdon 的回答,我发现Tutorials Point 上的 Unix / Linux - Shell Basic Operators还包括与文件相关的运算符(以及其他有用的运算符)。

-b file     Checks if file is a block special file; if yes, then the condition becomes true.    [ -b $file ] is false.
-c file     Checks if file is a character special file; if yes, then the condition becomes true.    [ -c $file ] is false.
-d file     Checks if file is a directory; if yes, then the condition becomes true.     [ -d $file ] is not true.
-f file     Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true.  [ -f $file ] is true.
-g file     Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true.    [ -g $file ] is false.
-k file     Checks if file has its sticky bit set; if yes, then the condition becomes true.     [ -k $file ] is false.
-p file     Checks if file is a named pipe; if yes, then the condition becomes true.    [ -p $file ] is false.
-t file     Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true.  [ -t $file ] is false.
-u file     Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true.     [ -u $file ] is false.
-r file     Checks if file is readable; if yes, then the condition becomes true.    [ -r $file ] is true.
-w file     Checks if file is writable; if yes, then the condition becomes true.    [ -w $file ] is true.
-x file     Checks if file is executable; if yes, then the condition becomes true.  [ -x $file ] is true.
-s file     Checks if file has size greater than 0; if yes, then condition becomes true.    [ -s $file ] is true.
-e file     Checks if file exists; is true even if file is a directory but exists.  [ -e $file ] is true.
Run Code Online (Sandbox Code Playgroud)


don*_*l24 5

man testman [将为您提供测试命令的所有选项。在这种情况下,-n 正在测试以查看 $abc 的内容是否具有非零长度,而 -z 正在测试以查看 $xyz 的内容是否是零长度字符串。

  • 注意`man test`(总是?)给出了外部程序版本的手册页,它(至少对于 GNU-coreutils 版本)明确警告某些(大多数 IME)shell 具有可能不同的内置版本。 (2认同)