单分支 if 语句
if [ 条件判断式 ];then
程序
fi
我们编写一个程序,用来查看分区使用率是否超过了我们的预期,如果超过了则发出警告,程序如下:
#!/bin/bash
rate=$(df -h | grep /dev/vda1 | awk '{print $5}' | cut -d "%" -f 1)
if [ $rate -ge 5 ];then
echo "warn!"
fi
双分支 if 语句
if [ 条件判断式 ]
then
条件成立,执行程序
else
条件不成立,执行程序
fi
多分支 if 语句
if [ 条件判断式1 ]
then
条件成立,执行程序
elif [ 条件判断式2 ]
then
条件成立,执行程序
......
else
所有条件不成立,最后执行程序
fi
我们写一个文件名输入测试程序,根据输入的值判断该文件是属于目录还是普通文件。
#!/bin/bash
read -p "Please input a filename:" file
if [ -z "$file" ]
then
echo "Error!Please input a filename!"
exit 1
elif [ ! -e "$file" ]
then
echo "your input is not a file!"
exit 2
elif [ -f "$file" ]
then
echo "$file is a regulare file"
elif [ -d "$file" ]
then
echo "$file is a directory"
else
echo "$file is an other file"
fi
case 语句
case $变量名 in
"值1")
执行程序
;;
"值2")
执行程序
;;
*)
如果变量不是以上的值,执行此程序
;;
esac
例子如下:
#!/bin/bash
read -p "Please input a number" -t 15 num
case $num in
"1")
echo "this is 1"
;;
"2")
echo "this is 2"
;;
*)
echo "another number"
;;
esac
for 语句
for 变量 in 值1,值2,值3
do
程序
done
for (( 初始值;循环控制条件;变量变化 ))
do
程序
done
例子如下:
#!/bin/bash
s=0
for (( i=1;i<=100;i=i+1 ))
do
s=$(( $s+$i ))
done
echo "the number is $s"
while 语句
while [ 条件判断式 ]
do
程序
done
#!/bin/bash
s=0;
i=1;
while [ $i -le 100 ]
do
s=$(( $s+$i ))
i=$(( $i+1 ))
done
echo "the number is $s"
until 语句
until [ 条件判断式 ]
do
程序
done
#!/bin/bash
s=0
i=1
until [ $i -gt 100 ]
do
s=$(( $s+$i ))
i=$(( $i+1 ))
done
echo "the number is $s"