shell脚本之for循环

shell经常使用for循环写法

方式一:使用外部赋值实现

#!/bin/bash
sum=0
for i in {1..50}
do
let "sum+=i"
done
echo $sumshell

注:以上脚本实现计算从1加到50的总和!bash

方式二:使用for单循环实现

#!/bin/bash
for name in cat namelist
do
echo "$name"
done
echo "循环结束"ide

注:以上脚本实现打印列表中名字,打印完循环结束!测试

方式三:使用内嵌if多分支语句实现

#!/bin/bash
for ip in 192.168.152.{1..254}
do
ping -c 2 -i 0.1 -W 1 $ip &> /dev/null
if [ $? -eq 0 ]
then
echo "$ip is up !"
else
echo "$ip is down !"
fi
donethis

注:以上脚本实现批量测试哪一个IP地址不通(-c 2 是ping两个包,-i 0.1 是指ping通第一个包到ping第二个包的时间间隔是0.1秒, -W 1 是指若是ping不通,等待的时间间隔是1秒)code

方式四:使用for循环内嵌for循环实现

#!/bin/bash
for month in Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
do
for week in 1 2 3 4
do
echo "this week is in $month of $week week !"
done
doneip

注:以上脚本实现循环打印每一个月的每周!it

方式五:使用for循环内嵌if单分支实现

#!/bin/bash
for file in *.sh
do
if [ -f $file -a ! -x $file ]
then
chmod +x $file
echo "$file is have Permission !"
fi
doneio

注:以上脚本检查当前路径的脚本是否有执行权限,无权限的给予执行权限!(切记全部脚本都得和当前脚本在同一路径,不然须要根据实际状况修改for file in *.sh这句)for循环

相关文章
相关标签/搜索