五 流程控制
2 for语句
1) 使用in关键字循环
根据变量的不同取值,重复执行一组命令操作
格式:
for 变量名 in 取值列表
do
命令序列
done
例子11:循环
#!/bin/bash
for time in morning noon afternoon evening
do
echo $time
done
例子12:
#输入目录名,显示目录下所有内容.
#!/bin/bash
read -p "please input a filename!" -t 30 filename
if [ -z $filename ];then
echo "please input!!!!!!"
exit 1
fi
#如果字符串为空,报错跳出
if [ ! -e $filename ]
then
echo "$filename not cunzai!!"
exit 2
fi
#如果文件不存在,报错跳出
if [ ! -d $filename ]
then
echo "$filename is not driectory"
exit 3
fi
#如果不是目录,报错跳出
file=`ls $filename`
for test in $file
do
echo $test
done
2)数值加加循环
例子13:
#/bin/bash
s=0
for ((i=1;i<=100;i=i+1))
do
s=$(($s+$i))
done
echo $s
3 while循环语句
重复测试指定的条件,只要条件成立则反复执行对应的命令操作
格式:
while 命令或表达式
do
命令列表
done
例子14:
批量添加用户
#!/bin/bash
i=1
while [ $i -le 20 ]
do
useradd stu$i
echo "123456" | passwd --stdin stu$i &> /dev/null
i=`expr $i + 1`
done
例子15:
批量删除用户
#!/bin/bash
aa=`cat /etc/passwd | grep "/bin/bash"|grep -v "root"|cut -d ":" -f 1`
for i in $aa
do
userdel -r $i
done
例子16:
批量添加
#!/bin/bash
aa=10
for ((i=1;i<=$aa;i=i+1))
do
useradd stu$i
echo "123456" | passwd --stdin stu$i &> /dev/null
echo $i
done
4 case多重分支语句
根据变量的不同取值,分别执行不同的命令操作
例子17:
打印选择列表,输出选择
#!/bin/bash
echo -e "shanghai: 1\n"
echo -e "beijing: 2\n"
echo -e "chengdu: 3\n"
read -p "input your choice:" -t 30 choi
case $choi in
"1")
echo "shanghai!!!"
;;
"2")
echo "beijing!!!"
;;
"3")
echo "chengdu!!!"
;;
*)
echo "qing chongxin shuru!"
;;
esac