标签:
记录几个循环相关的简单例子
1. 等待输入预期的内容
#!/bin/bash until [ "$yn" == "yes" -o "$yn" == "YES" ] do read -p "Please input yes/YES to stop this progras: " yn done echo "OK! you input the correct answer. "
等待输入预期的内容才退出
也可用while实现
2. 多数字求和
while实现
i=0 s=0 while [ "$i" != "100" ] do i=$(($i + 1)) s=$(($s + $i)) done echo "The result of ‘1+2+..+100‘ is ==> $s "
用for实现
#!/bin/bash s=0 read -p "Please input a number, I will count for 1+2+3+...+your_input: " nu for (( i=1; i<=$nu; i=i+1 )) do s=$(($s + $i)) done echo "The result of ‘1+2+..+100‘ is ==> $s "
执行结果
3. 字符串处理
for循环对文件名逐个处理
#!/bin/bash for var in `ls` do echo $var done
执行结果如下
for循环处理用户信息
#!/bin/bash users=$(cut -d : -f1 /etc/passwd) for username in $users do id $username finger $username done
for循环查找指定ip地址的连通性
#!/bin/bash network="192.168.1" for sitenu in $(seq 97 110) do ping -c 1 -w 1 ${network}.${sitenu} &> /dev/null && result=0 || result=1 if [ "$result" == 0 ]; then echo "Server ${network}.${sitenu} is UP" else echo "Server ${network}.${sitenu} is DOWN" fi done
执行结果:
标签:
原文地址:http://www.cnblogs.com/zhanglong71/p/shell.html