shell 脚本for

2019/03/04 11:30
阅读数 16

用法:
for 变量名 in 变量遍历列表
do
循环语句
done #循环结束标志
###########################################
实战:用户管理(批量添加用户)
方法一:
vi for01_useradd.sh
userlist=$( cat user.list )
for user in $userlist
do
user_a=$(grep -w "$user" /etc/passwd | awk -F : '{print $1}')
if [ $user_a = $user ]
then
echo "the user $user is already exist."
else
useradd $user 2>> /dev/null
echo "user $user is added"
fi
done
[root@bogon ~]# cat user.list
user_1

user_2
user_3
user_4
user_5
[root@bogon ~]# bash for01_useradd.sh
user user_1 is added
user user_2 is added
user user_3 is added
user user_4 is added
user user_5 is added
[root@bogon ~]#
[root@bogon ~]# cat /etc/passwd
user_1:x:1001:1001::/home/user_1:/bin/bash
user_2:x:1002:1002::/home/user_2:/bin/bash
user_3:x:1003:1003::/home/user_3:/bin/bash
user_4:x:1004:1004::/home/user_4:/bin/bash
user_5:x:1005:1005::/home/user_5:/bin/bash
批量删除用户:
#!/bin/bash
userlist=$(cat user.list)
for user in $userlist
do
userdel -r $user 2>> /dev/null

if [ $? = 0 ]
then
echo "the user $user is deleted"
fi
done
[root@bogon ~]# bash userdel.sh
the user user_1 is delected
the user user_2 is delected
the user user_3 is delected
the user user_4 is delected
the user user_5 is delected
[root@bogon ~]# tail -5 /etc/passwd
sddm:x:980:977:Simple Desktop Display Manager:/var/lib/sddm:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/sbin/nologin
nginx:x:979:976:Nginx web server:/var/lib/nginx:/sbin/nologin
fedmsg:x:978:973:FedMsg:/usr/share/fedmsg:/sbin/nologin
[root@bogon ~]#
方法一优化:
我们发现,在用方法一批量添加用户时,当用户不存在时,会有报错信息,查看运行过程如

[root@bogon ~]# bash -x for01_useradd.sh
++ cat user.list

+ userlist='user_1
user_2
user_3
user_4
user_5'
+ for user in $userlist
++ grep user_1 /etc/passwd
++ awk -F : '{print $1}'
+ user_a=
+ '[' = user_1 ']'
for01_useradd.sh: line 6: [: =: unary operator expected
+ useradd user_1
+ echo 'user user_1 is added'
user user_1 is added
在进入循环后,我们首先查找/etc/passwd下,是否存在用户$user,
但是,在运行过程中,我们发现当这个用户不存在时user_a数值为空,判断条件就会少了一
个比较值,而造成判断条件为[ = user_1 ],这时系统就会报错
为了避免系统报错,我们可以使用-z或-n选项来判断user_a变量是否为空
#!/bin/bash
userlist=$(cat user.list)
for user in $userlist
do
user_a=$(grep $user /etc/passwd | awk -F : '{print $1}')

if
# [ $user_a = $user ]
[ ! $user_a -z ] && [ $user_a = $user ]
then
echo "the user $user is already exist."
else
useradd $user
echo "user $user is added"
fi
done
方法二:
我们也可以采取另外一种方法,来批量添加用户
#!/bin/bash
userlist=$(cat user.list )
for user in $userlist
do
useradd $user 2>> /dev/null
if [ $? -eq 0 ]
then
echo "123456" | passwd --stdin $user >> /dev/null
echo "useradd success!"
else
echo "the user $user is already exist."

done
实战:批量测试IP地址是否连通
#!/bin/bash
ip_list=$(cat ip.list)
for ip in $ip_list
do
ping -w 3 -c 3 -i 0.2 $ip >> /dev/null
if [ $? -eq 0 ]
then
echo "the $ip is up"
else
echo "the $ip is down"
fi
done

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部