1.if判断

①简单判断,如果满足条件,返回OK

#!/bin/bash
a=5
if [ $a -gt 3 ]
then
   echo "OK"
fi
[root@localhost test_shell]# ./test.sh
OK

②两个条件时,可以使用elif及else

#!/bin/bash
a=5
if [ $a -lt 3 ]
then
   echo "<3"
elif [ $a -lt 6 ]
then
   echo " <6"
else
   echo "Not OK"
fi
[root@localhost test_shell]# ./test.sh
 <6
[root@localhost test_shell]# bash -x test.sh
+ a=5
+ '[' 5 -lt 3 ']'
+ '[' 5 -lt 6 ']'
+ echo ' <6'
 <6

逻辑判断表达式中的常用符号:

-lt:小于

-gt:大于

-eq:等于

-le:小于等于

-ge:大于等于

||:或者

&&:并且

!:非

2.文件目录属性判断

①-f选项判断文件是否存在

#!/bin/bash
a=/tmp/test_shell/f_exist.txt
if [ -f $a  ]
then
   echo "$a exist"
else
   touch $a
   echo "File Created"
fi

执行结果如下:

[root@bogon test_shell]# sh -x test.sh
+ a=/tmp/test_shell/f_exist.txt
+ '[' -f /tmp/test_shell/f_exist.txt ']'
+ touch /tmp/test_shell/f_exist.txt
+ echo 'File Created'
File Created
[root@bogon test_shell]# sh -x test.sh
+ a=/tmp/test_shell/f_exist.txt
+ '[' -f /tmp/test_shell/f_exist.txt ']'
+ echo '/tmp/test_shell/f_exist.txt exist'
/tmp/test_shell/f_exist.txt exist

②-d选项判断目录是否存在,-e则表示检查文件或者目录是否存在

#!/bin/bash
a=/tmp/test_shell/folder_test
if [ -d $a  ]
then
   echo "Folder:$a exist"
else
   mkdir $a
   echo "Folder Created"
fi

执行结果如下:

[root@bogon test_shell]# sh -x test_folder.sh
+ a=/tmp/test_shell/folder_test
+ '[' -d /tmp/test_shell/folder_test ']'
+ mkdir /tmp/test_shell/folder_test
+ echo 'Folder Created'
Folder Created
[root@bogon test_shell]# sh -x test_folder.sh
+ a=/tmp/test_shell/folder_test
+ '[' -d /tmp/test_shell/folder_test ']'
+ echo 'Folder:/tmp/test_shell/folder_test exist'
Folder:/tmp/test_shell/folder_test exist

③判断文件是否可读(-r),可写(-w),可执行(-x)

#!/bin/bash
a=/tmp/test_shell/readable.sh
if [ -r $a  ]
then
   echo "$a readable"
fi

执行结果如下:

[root@bogon test_shell]# sh -x readable.sh
+ a=/tmp/test_shell/readable.sh
+ '[' -r /tmp/test_shell/readable.sh ']'
+ echo '/tmp/test_shell/readable.sh readable'
/tmp/test_shell/readable.sh readable