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"
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
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
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