shell中的条件表达式

条件表达式返回的结果都为布尔型

  真为1,假为0

条件测试的表达式

  [expression]

  [[expression]]

  test expression

  这三种条件表达式的效果是一样的

比较符

  整数比较

  -eq:比较两个整数是否相等,$A -eq $B

  -ne:测试两个整数是否不等,不等则为真,等则为假

  -gt:大于为真,小于为假

  -lt:小于为真,大于为假

  -ge:大于或者等于

  -le:小于或者等于

  

  -e  File  测试文件是否存在

  -f  File  测试文件是否是普通文件

  -d  File 测试指定路径是否是目录

  -r  File 测试文件是否有写的权限

  -w  File 测试文件是否有写的权限

  -x  File测试文件是否有执行的权限

  -z:判断指定的变量是否存在值

  -n:测试字符是否为空 非空为真(0)

  -s:文件的大小非0时为真

  !:逻辑非

 双目:

  == 相等为真

  != 不等为真

  >  大于为真

  <  小于为真

  -a:逻辑与   都为真才为真

  -o:逻辑或  一个为真就为真

test expression  

  expression为条件表达式

  if test  (表达式为真) 
  if test !表达式为假 
  test 表达式1 –a 表达式2                  两个表达式都为真 
  test 表达式1 –o 表达式2                 两个表达式有一个为真 

摩根定律

  !(A  -a  B)= !A  -o  !B

  !(A  -o  B)= !A  -a  !B

逻辑符

 &&:逻辑与,都为真则为真 

  如果第一个条件是真的,需要对第二个条件进行判断

  如果第一个条件是假的,不需要对第二个条件进行判断,结果已经确定为假。

 ||:逻辑或,一个为真则为真 

  当第一个条件为真的时候,不在去判断第二条件,因为第一个表达式已经决定了整个表达式为真

  只有当第一个表达式为假的时候才回去判断第二个表达式

应用于脚本:

  这是一个用来比较两个整数大小的脚本

#!/bin/sh
read -p "Pls input two nums:" a b   
[ -z $a ] || [ -z $b ] && {
        echo "Pls input two nums"
        exit 1
}

expr $a + 1 &>/dev/null
RETRAVL1=$?

expr $b + 1 &>/dev/null
RETRAVL2=$?

test  $RETRAVL1 -eq 0 -a $RETRAVL2 -eq 0||{
        echo "Pls input two nums"
        exit 2
}

[ $a -lt $b ] && echo "$a < $b"

[ $a -eq $b ] && echo "$a = $b"

[ $a -gt $b ] && echo "$a > $b"

[root@BASE scripts]# sh var.sh
Pls input two nums:1 2
1 < 2
[root@BASE scripts]# sh var.sh
Pls input two nums:2 1
2 > 1
[root@BASE scripts]# sh var.sh
Pls input two nums:1 1
1 = 1
[root@BASE scripts]# sh var.sh
Pls input two nums:a
Pls input two nums
[root@BASE scripts]# sh var.sh
Pls input two nums:1
Pls input two nums
[root@BASE scripts]# sh var.sh
Pls input two nums:1 2 3

 

 说明:一下是学习shell的时候练习的小脚本,其中也包含了一些条件判断的语句,因为刚学,写的比较烂,众网友不看也罢。

注:该脚本用于测试某目录下的某文件是否存在
#!/bin/sh Path=/server/scripts File=test.sh if [ ! -d $Path ] then echo "No such dir,is creatinig $Path" mkdir $Path -p fi if [ ! -f $Path/$File ] then echo "No such file,is creating $File" touch $Path/$File exit 0 fi echo "ls -l $Path/$File" ls -l $Path/$File ~

另一种写法;

#!/bin/sh
Path=/serer/scripts
File=test.sh

if [ ! -e $Path/$File ]
then
echo "No such file or directory.is creating......"
mkdir -p $Path &>/dev/null
touch $Path/$File
exit 0
fi

echo $(ls -l $Path/$File)

 内存小于400M就报警的shell脚本

#!/bin/sh
LeftMem=`free -m|grep "Mem"|tr -s " "|cut -d" " -f4`     //free -m 以兆为单位显示

if [ $LeftMem -lt 400 ]
then
  echo "mem is not enough" |mail -s "mem warninig at $(date +%F-%X)" 18348087798@163.com         //要先安装sendmail
fi
原文地址:https://www.cnblogs.com/along1226/p/4957148.html