shell 之 if 判断
一、shell 示例
#!/bin/bash
str="Hello"
if [ -n "$str" ]; then
echo "The string is not empty."
else
echo "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)
字符串判断:
[ -z STRING ]
- True if the length of "STRING" is zero.
[ -n STRING ] or [ STRING ]
- True if the length of "STRING" is non-zero.
[ STRING1 == STRING2 ]
- True if the strings are equal.
"=" may be used instead of "==" for strict POSIX compliance.
[ STRING1 != STRING2 ]
- True if the strings are not equal.
[ STRING1 < STRING2 ]
- True if "STRING1" sorts before "STRING2" lexicographically in the current locale.
[ STRING1 > STRING2 ]
- True if "STRING1" sorts after "STRING2" lexicographically in the current locale.
数字判断:
[ ARG1 OP ARG2 ]
- "ARG1" and "ARG2" are integers.
- "OP" is one of:
-eq : equal to,
-ne : not equal to,
-lt : less than,
-le : less than or equal to,
-gt : greater than,
-ge : or greater than or equal to.
These arithmetic binary operators return true if "ARG1" is [OP] "ARG2", respectively.
Ref