在Shell脚本中,使用if
语句进行复杂的条件判断时,可以结合多种条件测试命令和逻辑运算符来实现。以下是一些复杂条件判断的例子:
示例1:多条件与(and)操作
#!/bin/bash
# 判断两个条件是否同时为真
value1=5
value2="Hello"
if [ "$value1" -eq 5 ] && [ "$value2" = "Hello" ]; then
echo "Both conditions are true"
else
echo "At least one condition is false"
fi
示例2:多条件或(or)操作
#!/bin/bash
# 判断两个条件是否有任意一个为真
file1_exists=$(test -e file1.txt; echo $?)
file2_exists=$(test -e file2.txt; echo $?)
if [ "$file1_exists" -eq 0 ] || [ "$file2_exists" -eq 0 ]; then
echo "At least one file exists"
else
echo "Neither file exists"
fi
# 或者更简洁的写法:
if test -e file1.txt || test -e file2.txt; then
echo "At least one file exists"
else
echo "Neither file exists"
fi
示例3:嵌套if语句
#!/bin/bash
number=10
if [ "$number" -gt 0 ]; then
if [ "$number" -lt 20 ]; then
echo "The number is between 0 and 20 (inclusive)"
else
echo "The number is greater than 20"
fi
else
echo "The number is less than or equal to 0"
fi
# 使用双括号[[ ]]语法简化嵌套条件
if [[ $number -gt 0 && $number -lt 20 ]]; then
echo "The number is between 0 and 20 (inclusive) using double brackets"
fi
示例4:模式匹配与文件测试结合
#!/bin/bash
filename="example.log"
if [[ -f "$filename" && "$filename" == *.log ]]; then
echo "The file '$filename' exists and has the .log extension"
else
echo "The file either doesn't exist or doesn't have the .log extension"
fi
以上是几种常见的复杂条件判断场景,通过组合不同的条件测试和逻辑运算符,可以在Shell脚本中构建更加复杂和精细的控制流程。