条件测试
test 表达式 或者 [ 表达 ] (中括号要打space)
字符串
== != -z(非空)
[root@room9pc01 opt]# test abc==abc
[root@room9pc01 opt]# echo $?
0
[root@room9pc01 opt]# [ 5 == 3 ]
[root@room9pc01 opt]# echo $?
1
[root@room9pc01 opt]# test abc == bcd
[root@room9pc01 opt]# echo $?
1
[root@room9pc01 opt]# [ -z $c ]
[root@room9pc01 opt]# echo $?
1
[root@room9pc01 opt]# [ ! -z $c ] (!与- 之间有空格)(_是否为空)
[root@room9pc01 opt]# echo $?
0
2.数字测试
-eq
-ne
-gt
-ge
-lt
-le
3.文件测试
-e 文件是否存在
-f 是否存在,并且为普通 (尽量写清楚绝对路径)
-d 文件是否存在,并且为目录
-r
-w
-x
[root@room9pc01 opt]# touch 123
[root@room9pc01 opt]# [ -x 123 ]
[root@room9pc01 opt]# echo $?
1
(管理员对文件都有读写权限,但是对X权限有限制)
4.逻辑测试
&& 之前任务成功才执行之后任务
|| 之前任务失败才执行之后任务
; 前后都执行
###########################################################
if 选择结构
1.单分支 2. 双分支 3.多分支
[root@room9pc01 opt]# bash test08.sh
dul
[root@room9pc01 opt]# cat test08.sh
#!/bin/bash
if [ -e /opt/abc ];then
echo 'xiaodii'
fi
if [ -d /etc/opt ]; then
echo 'dul'
fi
-----------------------------------------------------
[root@room9pc01 opt]# cat test08.sh
#!/bin/bash
if [ -e /opt/abc ];then
echo 'xiaodii'
else
echo 'buzai';touch /opt/abc
fi
[root@room9pc01 opt]# bash test08.sh
buzai
[root@room9pc01 opt]# ls
123 abc test02.sh test04.sh test06.sh test08.sh
2020-04-09_log.tar.gz test01.sh test03.sh test05.sh test07.sh
-------------------------------------------------------------------------------------------
[root@room9pc01 opt]# bash test08.sh
qingshurunidechegnji : 90
you
[root@room9pc01 opt]# cat test08.sh
#!/bin/bash
#
read -p 'qingshurunidechegnji : ' n
if [ $n -ge 90 ];then
echo 'you'
elif [ $n -ge 80];then
echo 'liang'
elif [ $n -ge 70 ];then
echo 'cha'
else
echo 'bujige'
fi
#######################################################
[root@room9pc01 opt]# echo $RANDOM (随机数)
15261
$[RANDOM%16] 参数0到15之内的数
--------------------------------------------------------------------------------
循环
for 变量名 in 值 值可以为任意,只需要用space隔开.或者 {1..9} (不支持变量的循环次)
do (seq 从一个数到另一个数 及 之间的所有整数)(支持变量的循环次数)
命令 ( ` seq $n `)
done
[root@room9pc01 opt]# cat test11.sh
#!/bin/bash
a=0 b=0
for i in {80..100}
do
ping -c 3 -i 0.2 -w 1 183.62.195.$i &> /dev/null
if [ $? -eq 0 ];then
echo '通了'
let a++
else
echo '不通'
let b++
fi
done
echo $a
echo $b
-------------------------------------------------------------------------------
while循环 可以实现无限次的循环
while 条件测试
do
命令序列
done