shell 条件语句

shell 条件语句

#!/bin/bash
# 条件语句
NUM1=100
NUM2=200

if (($NUM1 > $NUM2));then
    echo "$NUM1 greater than $NUM2 !"
else
    echo "$NUM1 less than $NUM2 !"
fi

判断目录是否存在,判断文件是否存在
-f 判断文件 中括号
-d 判断目录
-a and
-o or
-z 空字符串
-eq 等于
-ne 不等于
-lt 小于
-gt 大于
-le 小于等于
-gt 大于等于

#!/bin/bash
# 条件语句
NUM1=100
NUM2=200

if [ $NUM1 -gt $NUM2 ];then
    echo "$NUM1 greater than $NUM2 !"
else
    echo "$NUM1 less than $NUM2 !"
fi
#!/bin/bash
# 条件语句

if [ ! -d  "doc" ];then
    mkdir doc
    echo "目录创建成功"
else
    echo "目录已存在"
fi

注意空格。

#!/bin/bash
# 条件语句

if [ ! -f  "test.txt" ];then
    touch test.txt
    echo "文件创建成功"
else
    echo "文件已存在"
fi

> 覆盖
>> 追加

#!/bin/bash
# 条件语句
score=85
if [ $score -gt 80 ];then
    echo "very good"
elif [ $score -gt 75 ];then
    echo "good"
elif [ $score -gt 60 ];then
    echo "pass"
else
    echo "not pass"
fi
#!/bin/bash
# 条件语句
score=85
if [[ $score -gt 80 ]];then
    echo "very good"
elif [[ $score -gt 75 ]];then
    echo "good"
elif [[ $score -gt 60 ]];then
    echo "pass"
else
    echo "not pass"
fi

推荐使用双中括号。

[test 是 Shell 的内部命令,而[[是Shell的关键字。

[[中使用&&||表示逻辑与和逻辑或。[中使用-a-o 表示逻辑与和逻辑或。

[[]] 增强方括号用法,常用于字符串的比较。主要用于条件测试, 双括号中的表达式可以使用 &&, ||, <, > 等 C 语言语法。

猜你喜欢

转载自www.cnblogs.com/jiqing9006/p/10029121.html