LINUX SHELL条件判断

本文详细介绍了Shell脚本中算术、字符串及文件属性等条件判断的使用方法,并提供了多个示例来展示如何进行条件判断。
算术运算的条件判断
[] [[]]:
-eq
-ne
-lt
-le
-gt
-ge

(( )):
>
<
>=
<=
=

[root@monitor ~]# if (( 2 == 3));then echo '123'; fi
[root@monitor ~]# if (( 2 >= 3));then echo '123'; fi
[root@monitor ~]# if (( 2 <= 3));then echo '123'; fi
123
[root@monitor ~]# if (( 2 < 3));then echo '123'; fi
123
[root@monitor ~]# if (( 2 > 3));then echo '123'; fi



字符串的条件判断

-z
-n
=
==
!=
<
>

文件属性的条件判断

-f
-d
-c
-w
-L
-x
-e
-b
-r



#!/bin/bash
if [ -e demo.sh ];then
echo "文件存在"
fi

fpath="/etc/passwd"

if [ -e $fpath ];then
echo file exists;
else
echo file no exists;
fi


[ -e "/etc/hosts" ] || (echo '/etc/hosts not exist";exit 1)

if [ "$?" -eq 1 ];then
exit
fi

echo "/etc/hosts 文件存在"


declare -i a
a=20
if [ $a -eq 20 ];then
echo "var a 20"
fi


if [ $a -gt 10 ];then
echo 'var >10';
fi


if [ "$LOGNAME" != "ROOT" ];then
echo "root "
fi


if [ "Bill" >"Apple" ];then
echo " BILL >APPLE"
fi

str="Bill"
if [ -n $str];then
echo "234"
fi

 

#!/bin/bash
NUM1=100
NUM2=200
if (($NUM1 > $NUM2));then
echo "ok"
else
echo "ok1"
fi

 

#!/bin/bash
Dir=/tmp/20140909
if [ ! -d $Dir ];then
mkdir -p $Dir
echo -e "\033[32mthis $Dir exist\033[0m"
else
echo -e "\033[32mthis $Dir is exist,please exit.\033[0m"

fi


#!/bin/bash
FILES=/tmp/test.txt
if [ -f $FILES ];then
echo "ok">>$FILES
else
cat $FILES
fi

 

-a: 逻辑表达式 -a 逻辑表达式
-o: 逻辑表达式 -o 逻辑表达式

 

转载于:https://www.cnblogs.com/zengkefu/p/5522976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值