循环主要分为3种
1.for循环
for循环的基本语法结构是三步走
for ##条件do ##要做什么
done ##结束
借几个脚本来理解一下
1)10秒倒计时脚本
#!/bin/bash
for ((a=10;a>0;a--))
doecho -n " TIME $a"echo -ne "\r \r"sleep 1
done
2)如果想要自己输入的时间为倒计时呢
#!/bin/bash
read -p "please input the time you want count,eg 01 10 " i j
a=$i*60+$j
for ((b=$a;b>0;b--))
doecho -n " TIME $[b/60]:$[b%60] "echo -ne "\r"sleep 1
done
3)九九乘法表
#!/bin/bash##打印9*9乘法表
#1*1=1
#2*1=2 2*2=4
#3*1=3 3*2=6 3*3=9for i in $(seq 9)
dofor j in $(seq $i)doecho -ne "$i*$j=$(($i*$j))\t"doneecho -e "\n"
done
4)嵌套循环
#!/bin/bashfor((a=1;a<=3;a++))
doecho "Starting outside loop: $a"for((b=1;b<=3;b++))doecho "Inside loop: $b"done
done
2.if-else
if-else循环基本语法结构为
if ;then ##条件1
elif ;then ##条件2
........ ##可以有多个elif
else ##最后的条件
fi ##结束
当然其中最简单的结构就是只有一个if和结尾的fi,再稍微复杂一点就是if-else-fi结构,比较复杂的就是上面代码段中的。
1)如果用话存在输出,hello+用户名
#!/bin/bash
user=kiosk
if grep $user /etc/passwd;then echo "Hello $user"
fi
2)检测student用户是否存在,存在显示家目录的内容
#!/bin/bash
user=student
if grep $user /etc/passwd;thenecho "The files for user $user are:"ls -a /home/$user
elseecho "$user not exist!"
fi
3)查看是否被允许登陆
#!/bin/bashif [ "$1" == "student" ];thenecho "Welcome $1"
elif [ "$1" == "westos" ];thenecho "Welcome $1"
elif [ "$1" == "kiosk" ];thenecho "Welcome $1"
elif [ "$1" == "linux" ];thenecho "Welcome $1"
elseecho "You are not allowed!"
fi
3.while
while的基本语法结构为
while ##条件do ##做什么
done ##结束
1)新建westos{1..20}用户,并统一设置密码
#!/bin/bash
PREFIX="westos"
i=1
while [ $i -le 20 ]
douseradd -r ${PREFIX}$i &> /dev/nullecho "123456" | passwd --stdin ${PREFIX}$i &> /dev/null ##标准输入的方式更改密码((i++))
done
2)隔2秒输出依次系统启动时间
#!/bin/bash
while true
douptimesleep 2
done
4.case
case的结构如下面代码段中的程序
1)如果是允许用户输出允许,不是的话,输出sorry
#!/bin/bash
case $1 in
student|kiosk|linux|westos)echo "Welcome,$1";;
*)echo "sorry!";;
esac
5.练习题
运用本节所学内容,写一个交互式程序
#!/bin/bash
while true ##死循环
doecho -e "\033[31m A 显示主机IP \033[0m\033[32m B 显示磁盘剩余空间 \033[0m\033[33m C 显示系统运行时间 \033[0m\033[34m Q 退出系统 \033[0m
"
read -p "请输入你的选择:" charcase $char ina|A)ifconfig br0 | grep "inet " | awk '{print $2}';;b|B)df -h | awk 'NR==2{print "剩余空间大小为:"$4}';;c|C)uptime |awk '{print $3}' | awk -F, '{print $1}' | awk -F: '{print "系统已经运行了"$1"小时"$2"分钟"}';;q|Q)exit 0;;esac
done
OK~