bashでshellスクリプトforループのサンプルコード
例1 普通列挙
for i in 'apple’ 'meat’ 'sleep’ 'girl’
do
echo I like $i
done
結果:
arkgame.com@X:~$ bash for.sh
I like apple
I like meat
I like sleep
I like girl
例2 1+2+3+….100
#!/bin/bash
ans=0
for i in {1..100}
do
let ans+=$i
done
echo $ans
結果
5050.
例3 100以内に全ての奇数の和
for i in {1..100..2}
do
echo $i
done
seq
例4 shellでLANのHostをpingする
#!/bin/bash
PREFIX=192.168.1.
for i in `seq 100 110`
do
echo -n “${PREFIX}$i "
ping -c5 ${PREFIX}${i} >/dev/null 2>&1
if [ “$?" -eq 0 ];then
echo “OK"
else
echo “Failed"
fi
done
他の書き方
for i in {100..110}
結果:
arkgame.com@X:~$ bash ping.sh
192.168.1.100 Failed
192.168.1.101 Failed
192.168.1.102 OK
192.168.1.103 OK
192.168.1.104 OK
192.168.1.105 OK
192.168.1.106 Failed
192.168.1.107 Failed
192.168.1.108 Failed
192.168.1.109 Failed
192.168.1.110 Failed
例4 1~100の和を計算
#!/bin/bash
ans=0
for ((i=1;i<=100;i++))
do
let ans+=$i
done
echo $ans