shell编程-流程控制-for循环
for循环的写法主要有两种:
for 变量 in 值1 值2 值3 ... do 循环执行的操作 done
或者
for (( 初始值;
循环条件;
变量变化 )) do 循环执行的操作 done
说明:第一种写法主要用于循环次数不明确的情况;而第二种写法主要用于已知循环次数的情况。
示例1:打印时间
#!/bin/bash#打印时间for time in morning noon afternoon evening do echo "This time is $time!" done
这个for循环会循环四次,每次循环都把对应的值赋给变量time。
示例2:批量解压缩
#!/bin/bash#批量解压缩cd /tmpls *.tar.gz > ls.logfor i in $(cat ls.log) do tar -zxf $i &>/dev/null donerm -rf /tmp/ls.log
示例3:求1到100的和
#!/bin/bash#求1到100的和s=0for (( i=1;
i<=100;
i=i+1 )) do s=$(( $s+$i )) doneecho "The sum is $s"
示例4:批量添加新用户
#!/bin/bash#批量添加新用户#Author: rootread -p "Please input username: " nameread -p "Please input the number of users: " numread -p "Please input the password of users: " passif [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ] then if [ "$num" == 0 ];
then echo "The number must greater than 0!" exit 1 fi y=$(echo "$num" | sed '
s/^[0-9]*$//g'
)#将数字替换为空,以便判断变量num是否是数值 if [ -z "$y" ] then for (( i=1;
i<=$num;
i=i+1 )) do useradd "$name$i" &>/dev/null echo $pass | passwd --stdin "$name$i" &>/dev/null done else echo "the number of users must be a integer!" exit 2 fi else echo "Please input correct value!" exit 3fi
说明: exit后面跟数字,可以指定脚本执行后 $? 的值,后面的代码不会执行。
注意: 在调用变量时,最好用双引号括起来。如:”