5. 流程控制
5.1 if语句
(1)格式:
格式1 |
格式2 |
多分支if |
if [ 条件判断式 ];then #程序 else #程序 fi |
if [ 条件判断式 ] then #程序 else #程序 fi |
if[ 条件判断1 ];then #程序 elif [ 条件判断2 ];then #程序 else #程序 fi |
(2)注意事项
①if语句使用fi结尾,和一般语言使用大括号结尾不同
②[ 条件判断式 ]就是使用test命令判断,所以中括号和条件判断式之间必须有空格。
③then后面跟符合条件之后执行的程序,可以放在[]之后,用“;”分割。也可以换行写入,就不需要“;”了
【编程实验】1.统计根分区大小
#!/bin/bash #统计根分区使用率 #Author: SantaClaus #把根分区使用率作为变量rate的值 rate=$(df -h | grep "/dev/sda5" | awk '{print $5}' | cut -d "%" -f 1) if [ $rate -ge 80 ];then echo "Warning! /dev/sda5 is full!" else echo "usage:$rate%" fi
【编程实验】2.判断文件类型
#!/bin/bash #判断用户输入的是什么文件 #Author: Santa Claus #接收键盘输入,并赋予变量file read -p "Please input a file name:" file if [ -z "$file" ]; then #判断file变量是否为空 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 regular file!" elif [ -d "$file" ];then #是否为目录 echo "$file is a directory" else echo "$file is an other file!" fi
5.2 case语句
(1)case和if…elif…else的区别
两者都是多分支条件语句,但与if多分支语句不同的是,case语句只能判断一种关系,而if语句可以判断多种条件关系。
(2)case语句的格式
case $变量名 in "值1") #程序1 ;; "值2") #程序2 ;; *) #程序3 ;; esac
【编程实验】判断用户输入
#!/bin/bash #判断用户输入 #Author:Santa Claus read -p "Please choose yes/no: " -t 30 choice case $choice in "yes") echo "Your choose is yes!" ;; "no") echo "Your choose is no!" ;; *) echo "Your choose is error!" esac
5.3 for循环
(1)语法
语法1 |
语法2 |
for 变量 in 值1 值2 值3… do #程序 done |
for(( 初始值;循环控制条件;变量变化)) do #程序 done |
(2)应用举例
【编程实验】批量添加用户
#!/bin/bash #批量添加用户 #Author: Santa Claus read -p "Please input user name: " -t 30 name read -p "Please input the number of users: " -t 30 num read -p "Please input the password of users: " -t 30 pass if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ];then #判断输入num是否是数字 y=$(echo $num | sed 's/[0-9]//g') #将数字替换为空 if [ -z "$y" ];then for((i=1;i<=$num;i=i+1)) do #添加用户,不显示操作结果 /usr/sbin/useradd $name$i &>/dev/null #添加密码,不显示操作结果 echo $pass | /usr/bin/passwd --stdin $name$i &>/dev/null done fi fi
5.4 while循环和until循环
(1)while的语法
while [ 条件判断式 ] do #程序 done
注意:while循环是不定循环,也称作条件循环。只要条件判断式成立,循环就会一直继续,直到条件判断式不成立,循环才会停止。这就和for的固定循环不太一样。
(2)until循环的语法
until [ 条件判断式 ] do #程序 done
注意:until,和while循环相反,在until循环时只要条件判断式不成立则进行循环,并执行循环程序。一旦循环条件成立,则终止循环。
【编程实验】while和until循环
#!/bin/bash #从1加到100 #Author: Santa Claus #方法1:通过while i=1 s=0 while [ $i -le 100 ] #小于等于100 do s=$(( $s + $i)) i=$(( $i + 1)) done echo "The sum is: $s " #方法2:until i=0 s=0 until [ $i -gt 100 ] #直至i大于100 do s=$(( $s + $i)) i=$(( $i + 1)) done echo "The sum is: $s "