善用判断式
$? && ||
test命令
[root@Dark ~]# test -e /hehehe
检查文件hehehe是否存在,并不会显示任何结果
[root@Dark ~]# test -e hehehe && echo "exist" || echo "Not exist"
关于两个整数之间的判定,例子: test n1 -eq n2;
-eq:两数值相等
-ne:两数值不等
-gt:n1大于n2
-lt:n1小于n2
-ge: n1大于等于n2
-le: n1小于等于n2
判定字符串的数据
test -z string:判定字符串是否为0,若为空字符串,则为true;
test -n string:判定字符串是否非为0,若为空字符串,则为false;
多重条件判定:
-a:两个条件同时成立
-o:任何一个条件成立
!:取反
空格
a.定义变量时, =号的两边不可以留空格
b.if语句 [ 符号的两边都要留空格
c.字符串比较, =两边要留空格
d. if 和then 在同一行 要加;
条件判断式
if [ 条件判断式 ];then
....
fi
#!/bin/bash
read -p "Please input(Y/N):" yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ];then
echo "OK,continue"
exit 0
fi
if [ "$yn" == "N" ] || [ "$yn" == "n" ];then
echo "Oh,interrupt!"
exit 0
fi
echo "I don't konw what your choice is" && exit 0
注意空格!
#!/bin/bash
read -p "Please input a num (1-10): " num
num2=`expr $RANDOM % 10 + 1`
if [ "$num" -gt "$num2" ];then
echo "You win!"
else
echo "You lose!"
fi
#!/bin/bash
read -p "Please input a num (1-10): " num
num2=`expr $RANDOM % 10 + 1`
if [ "$num" -gt "$num2" ];then
echo "You win!"
elif [ "$num" -eq "$num2" ];then
echo "Ping Ju!"
else
echo "You lose!"
fi
循环(loop)
while [ condition ]
do
...
done
s=0
i=0
while [ "$i" != "100" ]
do
i=$(($i+1))
s=$(($s+$i))
done
echo $s
for var in con1 con2 con3 ...
do
...
done
for animal in dog cat elephant
do
echo "There are ${animal}s.."
done
输出结果:
There are dogs..
There are cats..
There are elephants..
#!/bin/bash
network="192.168.0"
for sitenu in $(seq 100 125)
do
ping -c 1 -w 1 ${network}.${sitenu} &> /dev/null && result=0 || result=1
if [ "$result" == 0 ];then
echo "Server ${network}.${sitenu} is UP."
else
echo "Server ${network}.${sitenu} is DOWN."
fi
done
for ((初始值;限制值;执行步长))
do
...
done
#!/bin/bash
read -p "Please input a number:" num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i))
done
echo $s
!/bin/bash
for i in {1..22}
do
echo $i
done