一:shell中的运算
1、数学比较运算【整型】
在shell比较运算中没有< > =,可以用man test查看
运算符解释
-eq | 等于 |
-gt | 大于 |
-lt | 小于 |
-ge | 大于或等于 |
-le | 小于或等于 |
-ne | 不等于 |
test 1 -eq 1;echo $? 判断1等于1,如果返回0,则说明是正确的
如果要比较浮点型,就放大倍数,然后去掉小数点后面的0,比如1.5和2比较
[root@localhost shell]# test `echo "1.5*10"|bc|cut -d '.' -f1` -gt $((2*10));echo $?
1
【cut -d '.' -f1 代表以.为分隔符,打印第一个字段】
2、文件比较与检查
-d | 检查文件是否存在且为目录 |
-f | 检查文件是否存在且为文件 |
-e | 检查文件是否存在【可以判断文件或者目录】 |
-r | 检查文件是否存在且可读【注意如果是root超级用户,即使赋予000权限,echo $?依旧返回0】 |
-s | 检查文件是否存在且不为空 |
-w | 检查文件是否存在且可写 |
-x | 检查文件是否存在且可执行 |
-O | 检查文件是否存在并且被当前用户拥有【注意是大写O】 |
-G | 检查文件是否存在并且默认组为当前用户组 |
file1 -nt file2 | 检查file1是否比file2新 |
file1 -ot file2 | 检查file1是否比file2旧 |
3、字符串比较运算
【注意字符串要用引号】
== | 等于 |
!= | 不等于 |
-n | 检查字符串的长度是否大于0 |
-z(zero) | 检查字符串的长度是否为0 test -n "";echo $? |
4、逻辑运算
与或非 && || !
5、赋值运算
= 赋值运算符
二:if语法
1、单if语句
语句格式:
if [ condition ] #condition值为ture or false
then
commands
fi
例:【vi test2.sh】
if [ ! -d /tem/abc ]
then
mkdir -v /tem/abc #-v表示显示创建过程
echo "123"
echo "create /tem/abc ok"
fi
[root@localhost shell]# bash test2.sh
mkdir: created directory ‘/tmp/abc’
123
create /tmp/abc ok
2、if-then-else语句
语句格式
if [ condition ]
then
commands1
else
commands2
fi
例 :【vi test3.sh】
if [ $USER == 'root' ]
then
echo "管理员,你好"
else
echo "guest,你好"
fi
[root@localhost shell]# bash test3.sh
管理员,你好
3、if-then-elif语句
语句格式(略)
vi test4.sh
if [ $1 -gt $2 ]
then
echo "$1 > $2" #$1,$2就是从命令行传参的意思
elif [ $1 -eq $2 ]
then
echo "$1 = $2"
else
echo "$1 < $2"
fi
[root@localhost shell]# bash test4.sh 8 9
8 < 9
[root@localhost shell]# bash test4.sh 10 6
10 > 6
4.嵌套
vi test5.sh
if [ $1 -eq $2 ]
then
echo "$1 = $2" #$1,$2就是从命令行传参的意思
else
if [ $1 -gt $2 ]
then
echo "$1 > $2"
else
echo "$1 < $2"
fi
fi
[root@localhost shell]# bash test5.sh 4 5
4 < 5
[root@localhost shell]# bash test5.sh 7 6
7 > 6
三:if高级运用
(1)使用双括号进行运算
if (( 100%3+1>1 ));then
echo "yes"
else
echo "no"
fi #执行结果为yes
(2)匹配字符串
for i in r1 r2 r3 r4 #把r1,r2,r3,r4赋给i
do
if [[ $i = r* ]];then #匹配以r开头的元素
echo $i
fi
done #执行结果为r1 r2 r3 r4