我有一个 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)
小智 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)
man test或man [将为您提供测试命令的所有选项。在这种情况下,-n 正在测试以查看 $abc 的内容是否具有非零长度,而 -z 正在测试以查看 $xyz 的内容是否是零长度字符串。
| 归档时间: |
|
| 查看次数: |
298677 次 |
| 最近记录: |