3 循环结构
- Shell语言支持四种循环语句:for、while、until、select
- 工作中常用的是 for、while、until
for循环语法结构
- for循环主要用于确定次数的循环
- 第一种for循环的语法结构如下所示:
for 变量名 in 取值列表
do
循环体
done
[root@hdp-1 shell]
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."
[root@hdp-1 shell]
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 条件测试
do
循环体
done
- while循环语句会对条件测试进行判断,如果条件测试成立时,则执行do和done之间的循环体,直到条件测试不成立才停止循环。
- while循环语句实现批量用户创建
[root@hdp-1 shell]
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 条件测试
do
循环体
done
- until循环语句是在条件表达式不成立时,进入循环体执行指令,条件表达式成立时,终止循环。until的应用场景很罕见。
- until循环语句测试远程主机可达性
[root@hdp-1 shell]
host=www.baidu.com
until ping -c1 -w1 $host &>/dev/null
do
sleep 1
done
echo "$host up. "