笔记
语法一
for 变量 in 值1 值2 值3...
do
执行程序
done
#!/bin/bash
#打印时间
for time in morning afternoon evening
do
echo "This time is $time!"
done
[root@localhost sh]# ./for.sh
this time is moring!
this time is afternoon!
this time is evening!
#!/bin/bash
#批量解压缩脚本
cd /lamp
ls *.tar.gz > ls.log
for i in $(cat ls.log)
do
tar -zxf $i &>/dev/null
done
rm -rf /lamp/ls.log
语法二
for (( 初始值;循环控制条件;变量变化 ))
do
执行程序
done
#!/bin/bash
#从1加到100
s=0
for (( i=1;i<=100;i=i+1 ))
do
s=$(( $s+$i ))
done
echo "the sum of 1+2+...+100 is:$s"
[root@localhost ]# ./for2.sh
the sum of 1+2+...+100 is:5050
#!/bin/bash
#批量添加指定数量的用户
read -p "please input user name:" -t 30 name
read -p "please input number of users:" -t 30 num
read -p "please input the password of users:" -t 30 pass
if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ]
then
y=$(echo $num | sed 's/^[0-9]*$//g')
if [ -z "$y"]
then
for (( i=1;i<=$num;i=i+1 ))
do
/usr/sbin/useradd $name$i &>/dev/null
echo $pass | /usr/bin/passwd --stdin "$name$i" &>/dev/null
done
fi
fi