Always kee|

南哈哈

园龄:3年10个月粉丝:2关注:0

Shell循环:while until

shell循环:while untile

循环次数不一定是固定的

  可以固定

  可以不固定

 对文件进行处理优先使用while循环

 

语法结构

一、while语法结构
while 条件测试 #当条件测试成立(条件测试为真,执行循环体)
do
循环体
done
二、until语法结构
until 条件测试 #当条件测试成立(条件测试为假),执行循环体
do
循环体
done

示例

实现批量用户创建
#!/bin/bash
# for 是按照空格和tab键分隔,while是按照行处理。
while read line
do
if [ ${#line} -eq 0 ];then
echo "----------continue---------"
continue #跳过
#break
#exit 2
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 is created."
fi
fi
done < user.list
echo "ok..."
实现批量ssh处理
#!/bin/bash
#for ip in `cat ip.txt`
whlie read line
do
{
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
ssh $ip "sed -i '/^#UseDNS/c UseDNS no' /etc/ssh/sshd_config"
ssh $ip "sed -i '/^GSSAPIAuthentication/c GSSAPIAuthentication no' /etc/ssh/sshd_config"
ssh $ip "sed -i '/^SELINUX=/c SELINUX=enforcing' /etc/selinux/config"
ssh $ip "systemctl stop firewalld && systemctl disable firewalld"
ssh $ip "setenforce 0"
fi
}&
done
wait
echo "all ok ..."
测试远程主机连接
#!/bin/bash
IP=192.168.128.200
while ping -c1 ${IP} &>/dev/null
do
sleep 1
done
echo "${IP} is down.."
until ping -c1 ${IP} &>/dev/null
do
sleep 1
done
echo "${IP} is up.."
测试远程主机连接
#!/bin/bash
#for i in {2..254}
i=2
#while [ $i -le 254 ]
until [ $i -gt 254 ]
do
{
ip=192.168.128.$i
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip is up."
fi
}&
let i++
done
wait
echo "finish..."
数值运算
#!/bin/bash
i=1
#for i in {1..100}
#while [ $i -le 100 ]
until [ $i -gt 100 ]
do
#let sum=sum+$i
let sum+=$i
#echo $sum
let i++
done
echo $sum

 

本文作者:nanruosen

本文链接:https://www.cnblogs.com/nanruosen/p/16340288.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   南哈哈  阅读(49)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起