1.for 语句
for NUM in 1 2 3
for NUM in {1…3}
for NUM in `seq 1 3` 或者 for NUM in `seq 1 2 10`
do
done
注:seq 设定步长,每隔几个做一次
(1)正序输出1-10
#!/bin/bash
for i in {1..10}
do
echo $i
done

或者
#!/bin/bash
for i in `seq 1 10`
do
echo $i
done


(2)输出1,2,3
#!/bin/bash
for i in 1 2 3
do
echo $i
done


(3)利用for循环查看/mnt下的所有文件或子目录
#!/bin/bash
for i in `ls /mnt`
do
echo $i
done

测试:
[root@shell_example mnt]# vim test.sh
[root@shell_example mnt]# sh test.sh
calculator.sh
numtest.sh
test.sh
time_count1.sh
time_count.sh
[root@shell_example mnt]# ls
calculator.sh numtest.sh test.sh time_count1.sh time_count.sh


(4)输出1-10之间的奇数
#!/bin/bash
for i in `seq 1 2 10`
do
echo $i
done

测试:
[root@shell_example mnt]# vim jishu.sh
[root@shell_example mnt]# sh jishu.sh
1
3
5
7
9

(5)输出1-10之间的偶数
#!/bin/bash
for i in `seq 2 2 10`
do
echo $i
done

测试:
[root@shell_example mnt]# vim jishu.sh
[root@shell_example mnt]# sh jishu.sh
2
4
6
8
10

练习1:用for循环设计一个30秒的倒计时的定时器
#!/bin/bash
[ -z "$1" ]&&{
echo ERROR
exit
}
clear
for ((SEC=$1;SEC>0;SEC--))
do
echo -n "After ${SEC}s is end "
echo -ne "\r"
sleep 1
done

测试:
[root@shell_example mnt]# vim countdown.sh
[root@shell_example mnt]# sh countdown.sh
ERROR
[root@shell_example mnt]# sh countdown.sh 30


注意:
"After ${SEC}s is end "后一定要有空格,因为两位数和一位数所占的字符数不同,需要空格来占位
练习2:编写一个脚本,使其在没有输入任何内容的时候报错,连通主机是输出ip is up ,不能连通时输出ip is down
首先编辑一个文件写入需要测试的ip
[root@shell_example mnt]# vim ipfile
[root@shell_example mnt]# cat ipfile

脚本如下:
#!/bin/bash
[ -z "$1" ] && {
echo "plesae input filename"
exit
}
for i in `cat $1`
do
ping -c 1 -w 1 $i &>/dev/null && {
echo $i is up
} || {
echo $i is down
}
done

测试:
[root@shell_example mnt]# vim ip_check.sh
[root@shell_example mnt]# sh ip_check.sh
plesae input filename
[root@shell_example mnt]# sh ip_check.sh ipfile
172.25.254.1 is down
172.25.254.3 is down
172.25.254.10 is down
172.25.254.

本文详细介绍了Shell脚本中的循环语句,包括for、while、if和case,以及语句控制器如exit、break和continue。通过示例展示了如何使用这些语句进行条件判断、循环操作和流程控制。同时,还探讨了expect命令的使用,用于脚本交互。文章提供了多个练习题以帮助读者加深理解。
最低0.47元/天 解锁文章
1307

被折叠的 条评论
为什么被折叠?



