for 变量 in 值1 值2 ...值n
do
代码
done
#!/bin/bash sum=0 for num in 1 2 3 4 5 注释:可以把in后的数字用$@代替,接收从键盘输入 do sum=$((sum+num)) done echo "sum=$sum"
#!/bin/bash #批量解压缩 cd 目录 ls *.tar.gz>tmp.txt for i in $(cat tmp.txt) do tar -xzf $i &>/dev/null done rm -rf 目录/tmp.txt
for((初值;条件;改变初值))
do
代码
done
for((i=1;i<=100;i=(($i+1)))) 注释:for后跟的已经是双小括号(())了,(($i+1))可以直接写成i+1 do sum=$(($sum+$i)) done echo "sum=$sum"
运行结果:
[root@localhost ~]# ./myShell.sh sum=5050
#!/bin/bash #批量添加用户 read -p "请输入用户名前缀:" -t 20 namePrefix read -p "请输入用户数量:" -t 20 num read -p "请输入用户密码:" -t 20 pass if[ ! -z $name -a ! -z $num -a ! z $pass ] then n=$(echo $num|sed 's/[0-9]//g') if[ -z $n ] then for((i=1;i<=$num;i=i+1)) do /usr/sbin/useradd $namePrefix$i &>/dev/null echo $pass|/usr/bin/passwd --stdin $namePrefix$i &>/dev/null done fi fi