一、shell 示例
#!/bin/bashstr="Hello"
if [ -n "$str" ]; thenecho "The string is not empty."
elseecho "The string is empty."
fi
一、if 表达式说明
在 shell 脚本中,-n 选项用于条件表达式,以检查字符串是否为非空(non-empty)。
if [ -n "$str" ];
的分解:
-n
:测试字符串是否不为空(即,其长度大于零)。"$str"
:正在测试的变量。将其括在双引号中可防止变量为空或未设置时出现错误。[
和]
:这些是 test 命令的一部分,用于评估表达式。确保括号和括号内的内容之间有空格。
二、常见陷阱
务必确保 [ 之后和 ] 之前有一个空格,否则您会遇到语法错误。
正确的写法:
if [ -n "$str" ]; # 正确
if [ -n "$str"]; # 错误 (空格缺失)
三、Option 拓展
文件判断:
-e file exists
-f file is a regular file (not a directory or device file)
-s file is not zero size
-d file is a directory
-b file is a block device
-c file is a character device
-p file is a pipe
-L file is a symbolic link
-S file is a socket
-t file (descriptor) is associated with a terminal device
-r file has read permission (for the user running the test)
-w file has write permission (for the user running the test)
-x file has execute permission (for the user running the test)
Ref
- https://unix.stackexchange.com/a/628130/237356
END.