for 变量 in 列表 ;do
语句1
语句2
done
列表的生成
使用for循环遍历目录
#!/bin/bash #version:0.1 #author:ml #pragram:this scripts is print all files in directory DIR="/etc" for i in `ls $DIR`;do echo $i done使用for循环,复制/etc/fstab、/etc/inittab文件至/tmp/目录中,并重命名为原有的名称之后加当前日期,如第一个文件为/tmp/fstab-2013-07-15;#!/bin/bash #version:0.1 #author:ml #pragram:cp file to /tmp for i in fstab inittab ;do cp /etc/$i /tmp/$i-`date +%F` done练习:写一个脚本,计算100以内所有整数的和; #!/bin/bash # Sum=0 for I in {1..100}; do Sum=$[$Sum+$I] done echo "The sum is: $Sum." 练习:写一个脚本,计算100以内,所有偶数的和,以及所有奇数的和; #!/bin/bash EvenSum=0 OddSum=0 for I in `seq 1 2 100`; do OddSum=$[$OddSum+$I] done for I in `seq 2 2 100`; do EvenSum=$[$EvenSum+$I] done echo "Even Sum: $EvenSum; Odd Sum: $OddSum." 练习:写一个脚本,计算当前系统上所有用户的ID号之和; #!/bin/bash IDSum=0 for I in `cut -d: -f3 /etc/passwd`; do IDSum=$[$IDSum+$I] done echo "ID sum is: $IDSum."for ((初始条件;终止条件;异动项))do语句done#!/bin/bash #version:0.1 #author:ml #pragram:this pragram is and the sum from 1 to 100 declare -i i sum=0 for ((i=1;i<=100;i=i+1)) do sum=$[$sum+$i] done echo "the result is $sum"for 无穷循环for ((;1;))do语句donefor ((;1;)) do echo hello done
原文地址:http://168322.blog.51cto.com/158322/1411386