Shell条件测试
Shell条件测试
在Shell脚本中,条件测试可以使用三种格式:
- 格式1:使用
test命令。test命令允许您在Shell脚本中测试条件。例如:
if test $a -eq $b; then |
- 格式2:使用方括号
[]。方括号是test命令的等效符号。例如:
if [ $a -eq $b ]; then |
- 格式3:使用双方括号
[[]]。[[]]提供了更多的功能,比如模式匹配和正则表达式匹配,而不是仅仅测试变量是否存在或是否为空。例如:
if [[ $a -eq $b ]]; then |
文件比较
-e file: 检查文件是否存在。-f file: 检查文件是否是一个常规文件。-d file: 检查文件是否是一个目录。-s file: 检查文件是否非空。-r file: 检查文件是否可读。-w file: 检查文件是否可写。-x file: 检查文件是否可执行
示例:
文件测试条件是Shell脚本中常用的一种方式,用于检查文件的各种属性。以下是一些常见的文件测试条件及其用法:
文件是否存在 (
-e):if [ -e "$file" ]; then
echo "File exists."
fi文件是否是一个常规文件 (
-f):if [ -f "$file" ]; then
echo "File is a regular file."
fi文件是否是一个目录 (
-d):if [ -d "$file" ]; then
echo "File is a directory."
fi文件是否非空 (
-s):if [ -s "$file" ]; then
echo "File is not empty."
fi文件是否可读 (
-r):if [ -r "$file" ]; then
echo "File is readable."
fi文件是否可写 (
-w):if [ -w "$file" ]; then
echo "File is writable."
fi文件是否可执行 (
-x):if [ -x "$file" ]; then
echo "File is executable."
fi
数值比较
- 等于:
-eq(equal) - 不等于:
-ne(not equal) - 大于:
-gt(greater than) - 小于:
-lt(less than) - 大于等于:
-ge(greater than or equal to) - 小于等于:
-le(less than or equal to)
示例脚本:
!/bin/bash |
字符串比较
str1 = str2: 检查str1是否和str2相同str1 != str2: 检查str1是否和str2不同str1 < str2: 检查str1是否小于str2str1 > str2: 检查str1是否大于str2-n str1: 检查str1的长度是否不为0-z str1: 检查str1是否为0
示例脚本:
!/bin/bash |
复合条件测试
AND 操作符(&&)
语法:
[ condition1 ] && [ condition2 ] |
AND 操作符用于在两个条件都为真时返回真。
|
OR 操作符(||)
语法:
[ condition1 ] || [ condition2 ] |
OR 操作符用于在两个条件中至少有一个为真时返回真。
|
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 12零9!