加载中...
Linux Shell循环结构
发表于:2021-09-14 | 分类: 平台

3 循环结构

  • Shell语言支持四种循环语句:for、while、until、select
  • 工作中常用的是 for、while、until

for循环语法结构

  • for循环主要用于确定次数的循环
  • 第一种for循环的语法结构如下所示:
1
2
3
4
for 变量名 in 取值列表
do
循环体
done
  • for循环语句实现批量主机ping探测
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@hdp-1 shell]# cat for_ping.sh 
#!/bin/bash
for name in baidu 163 hao123
do
{
host=www.$name.com
ping -c1 -w1 $host &> /dev/null
if [ $? -eq 0 ];then
echo "$host" | tee -a host.txt
fi
}&
done
wait
echo "Mission Completed."
  • for循环语句实现文件中批量用户创建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@hdp-1 shell]# cat users_from_file.sh 
IFS=$'\n'
for line in `cat $1`
do
if [ ${#line} -eq 0 ];then
continue
fi
user=`echo "$line" | awk '{print $1}'`
pass=`echo "$line" | awk '{print $2}'`
id $user &>/dev/nuil
if [ $? -eq 0 ] ;then
echo "user $user already exists"
else
useradd $user
echo "$pass" | passwd --stdin $user &> /dev/null
if [ $? -eq 0 ];then
echo "$user created"
fi
fi
done

while循环语句语法结构

  • while循环语句的基本语法为:
1
2
3
4
while 条件测试
do
循环体
done
  • while循环语句会对条件测试进行判断,如果条件测试成立时,则执行do和done之间的循环体,直到条件测试不成立才停止循环。
  • while循环语句实现批量用户创建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@hdp-1 shell]# cat while_user.sh 
#!/bin/bash

while read line
do
if [ ${#line} -eq 0 ];then
echo "NULL"
continue
fi
user=`echo $line | awk '{print $1}'`
pass=`echo $line | awk '{print $2}'`
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user already exists."
else
useradd $user
echo "$pass"| passwd --stdin $user &>/dev/null
if [ $? -eq 0 ] ;then
echo "$user created ."
fi
fi
done < $1

until循环语句语法结构

  • until循环语句基本语法为:
1
2
3
4
until 条件测试
do
循环体
done
  • until循环语句是在条件表达式不成立时,进入循环体执行指令,条件表达式成立时,终止循环。until的应用场景很罕见。
  • until循环语句测试远程主机可达性
1
2
3
4
5
6
7
8
9
10
[root@hdp-1 shell]# cat until_ping.sh 
#!/bin/bash

host=www.baidu.com
until ping -c1 -w1 $host &>/dev/null
do
sleep 1
done
echo "$host up. "

上一篇:
Linux Shell基础
下一篇:
Linux Shell条件测试
本文目录
本文目录