在linux中要求从一个文件中读取用户名和密码,并批量添加账户
文件格式:1
2
3
4
5[root@localhost jeremy]# cat users.list
apple 12345
banana 123456
orange 123123
pear 123123
第一步:读取用户名和密码
- 创建
user.sh
文件 - 按行读取用户信息
1
2
3
4
5
6
7
8
9
10
11
12
13[root@localhost jeremy]# vim user.sh
[root@localhost jeremy]# cat user.sh
!/bin/sh
cat users.list | while read line
do
echo $line
done
[root@localhost jeremy]# ./user.sh
apple 12345
banana 123456
orange 123123
pear 123123
读取每一行内容并输出有多种方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 第一种 while
while read line
do
echo $line
done < filename
>>>>>>>>>>>>>>>>>>
第二种 while
cat filename | while read line
do
echo $line
done
>>>>>>>>>>>>>>>>>>
第三种 for
for line in `cat filename`
do
echo $line
done
>>>>>>>>>>>>>>>>>>
for循环在读取文件时,任何空白字符都可以作为其读取的分隔符.
while使用是换行符作为标记
ex:
for line in $(<users.list) 结果如下
apple
12345
banana
123456
orange
123123
pear
123123
第二步:分割用户名和密码
1 | [root@localhost jeremy]# cat user.sh |
第三步:批量添加用户
1 | [root@localhost jeremy]# cat user.sh |
第四步:完善脚本
以上脚本再运行一便,会发现新增用户不行了。但会修改了密码.应该增加一个用户是否存在的判断.另外所有非Shell内建命令都建议使用全路径,以避免由于环境变量的问题造成command not found。最后,脚本主体要尽量少使用变量,所以需要在脚本开头定义变量.如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16!/bin/bash
USER_INFO=/home/jeremy/users.list
USERADD=/usr/sbin/useradd
PASSWD=/usr/bin/passwd
CUT=/bin/cut
while read LINES
do
USERNAME=`echo $LINES | $CUT -f1 -d' '`
USERPASS=`echo $LINES | $CUT -f2 -d' '`
$USERADD $USERNAME
if [ $? -ne 0 ];then
echo "$USERNAME exists,skip set password"
else
echo $USERPASS | $PASSWD --stdin $USERNAME
fi
done < $USER_INFO