Shell中的循环判断语句(1)for语句

for语句的格式

for  (exp)            #判断条件,只要满足就执行循环,不满足则跳出
do  
     statement        #循环内容

done                  #结束循环 

实例:

计算1-100内的奇数和

#!/bin/bash
sum=0
for i in {1..100..2}
do
    let sum=$sum+$i
done

echo $sum

 

实战脚本

练习1:通过for循环计算阶乘

#!/bin/bash
read -p "Num:" num

result=1
for i in `seq $num`
do
    result=$[ $result * $i ]
done

echo "The result is:" $result

 

练习2:for循环批量新建用户

#!/bin/bash
#!/bin/bash
for count in {1..5}
do
    username="stu$count"
    id $username &> /dev/null
    if [ $? -eq 0];then
            echo "user %username exists"
    else
            useradd -d /rhome $username
            echo "user $username create success"
            echo 123 | passwd --stdin $username
    fi
done

你可能感兴趣的:(SHELL)