shell循环
shell循环的分类
1、for
2、while
3、until
for循环结构
for 变量 in 列表; do
循环体
done
在这种语法中,for 循环的次数取决于 in 后面值的个数(以空格分隔),有几个值就循环几次,并且每次循环都把值赋予变量。也就是说,假设 in 后面有三个值,for 会循环三次,第一次循环会把值 1 赋予变量,第二次循环会把值 2 赋予变量,以此类推。
1、求1加到100的和
这里要用到shell求和的命令
先学会求和就好说了https://www.qumai8.cn/2019/08/01/1999.html
#!/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