Shell总结05-循环

Shell总结05-循环

shell提供for、while、until三种循环方式

for loop

#!/bin/bash
# specific bakup confiig files
LIST="$(ls *.conf)"
for i in "$LIST"; 
	do cp "$i" "$i".bak 
done

#for循环样式
for NAME [in LIST ]; do 
	COMMANDS;
done

while loop

#!/bin/bash
#每隔5秒检查连接当前状态
while true; do
    http_code=`curl -I -m 10 -o /dev/null -s -w %{http_code} www.bing.com`
    echo ${http_code}
    sleep 5
done

#while 循环样式
while CONTROL-COMMAND; do 
	CONSEQUENT-COMMANDS;
done

until loop

#!/bin/bash
#每隔5秒检查链接当前状态,如果站点返回非200,每隔一秒变灰打印
while true; do
    http_code=`curl -I -m 10 -o /dev/null -s -w %{http_code} 192.168.56.104`
    echo ${http_code}
    until [ ${http_code} -eq 200 ]; do 
        echo "pages down with http_code: ${http_code}"
        sleep 1
    done
    sleep 5
done

IO重定向式的循环

#!/bin/bash

#读取test.conf文件每一行内容
while read line; do
   echo $line
done < test.conf

##在当前目录下的所有xml文件中搜索指定字符串
find "$PWD" -type f -name '*\.xml' | while read each_file
do
    echo "${each_file}:"
    grep  "$1" "$each_file" --color -r -n  
done

猜你喜欢

转载自www.cnblogs.com/elfcafe/p/13170615.html