shell编程—for循环

shell循环

shell循环的分类

1、for

2、while

3、until

for循环结构

for 变量 in 列表; do 
    循环体
done 

1、求1加到100的和

#!/bin/bash
# sum of 1 to 100

Sum=0
for i in {1..100};do
        Sum=$(($Sum+$i))
done
echo "Sum is $Sum"

shell编程—for循环

2、依次向/etc/passwd中的每个用户问好,并显示对方的shell,例如:
Hello,root,your shell: /bin/bash

#!/bin/bash
#

UserNum=`wc -l /etc/passwd | cut -d' ' -f1`

for i in `seq 1 $UserNum`; do
        UserName=`head -$i /etc/passwd | tail -1 | cut -d':' -f1`
        UserShell=`head -$i /etc/passwd| tail -1 |cut -d':' -f7`
        echo "Hello, $UserName, your shell: $UserShell"
done

shell编程—for循环

3、添加10个用户,user1-user10,密码同用户名,要求在不存在的情况下添加

#!/bin/bash 
#add user1-user10,passwd same as username

for i in {1..10}; do
        if id user$i &> /dev/null ;then
            echo "user$i exsits"
        else
            adduser "user$i" &> /dev/null
            echo "user$i" | passwd --stdin user$i &> /dev/null
        fi
done

4、删除10个用户,user1-user10
#!/bin/bash
#delete users


for i in {1..10} ; do
        if id user$i &> /dev/null ; then
            userdel -r user$i &> /dev/null
            echo "user$i delete finished!"
        else
            echo "user$i not exists!"
        fi
done

shell编程—for循环

5、接受一个参数,add或del,如果是add,则添加user1-user5,如果是del,则删除user1-user5

#!/bin/bash
#put in add,add user1-user10 or put in del,delete user1-user10

if [ $#  -ne 1 ] ; then
    echo "please input \"add\" or \"del\" "
    exit 10
fi

if [ $1 == add ] ; then
    for i in {1..5} ; do
        if ! id user$i &> /dev/null ;then
            useradd user$i &> /dev/null
            echo "user$i" | passwd --stdin user$i &> /dev/null
            echo "user$i add finished"
        else
            echo "user$i exists"
        fi
    done
elif [ $1 == del ]; then
    for i in {1..5} ; do
        if id user$i &> /dev/null ; then
            userdel -r user$i
            echo "user$i delete successful"
        else
            echo "user$i not exists"
        fi
fi

shell编程—for循环

转载于:https://blog.51cto.com/11193863/2319105

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值