脚本练习:建立用户

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了脚本练习:建立用户相关的知识,希望对你有一定的参考价值。

脚本练习:

要求:

1 编写的脚本script.sh /mnt/userfile /mnt/password

2 当要建立的用户已经存在不做任何操作

3 当脚本所指定文件个数少于两个显示:

pleasegive  me userfile  or  password file

4 当所给额文件行数不一致时显示:

/mnt/userfile‘s  line  is  different  from  /mnt/password‘s line

 

 

 

脚本如下:

#!/bin/bash

while [ "$#" -lt "2" ]

do

echo please give me userfle or password file

exit 1

done

COUNT=`wc -l $1 | cut -d " " -f 1`

COUNT1=`wc -l $2 | cut -d " " -f 1`

while [ $COUNT -ne $COUNT1 ]

do

echo "/mnt/userfile‘s line is different from /mnt/password‘s line"

exit 1

done

NUM=1

COUNT2=$[$COUNT+1]

while [ "$NUM" -lt "$COUNT2" ]

do

USERNAME=`sed -n ${NUM}p $1`

PASSWD=`sed -n ${NUM}p $2`

id $USERNAME &> /dev/null

while [ "$?" -ne "0" ]

do

useradd $USERNAME &> /dev/null

echo $PASSWD | passwd --stdin $USERNAME &> /dev/nul

done

NUM=$[$NUM+1]

done

 

 

 

 

测试:

 

[[email protected] ~]# cat /mnt/userfile

westos

westos1

westos2

westos3

westos4

[[email protected] ~]# cat /mnt/password

123

234

567

896

123

[[email protected] ~]# script.sh /mnt/userfile /mnt/password

[[email protected] ~]# id westos

uid=1008(westos) gid=1008(westos) groups=1008(westos)

[[email protected] ~]# id westos1

uid=1009(westos1) gid=1009(westos1) groups=1009(westos1)

[[email protected] ~]# id westos2

uid=1010(westos2) gid=1010(westos2) groups=1010(westos2)

[[email protected] ~]# id westos3

uid=1011(westos3) gid=1011(westos3) groups=1011(westos3)

[[email protected] ~]# id westos4

uid=1012(westos4) gid=1012(westos4) groups=1012(westos4)

[[email protected] ~]# vim /mnt/password

[[email protected] ~]# cat /mnt/password

123

234

567

896

123

123

[[email protected] ~]# script.sh /mnt/userfile /mnt/password

/mnt/userfile‘s line is different from /mnt/password‘s line

[[email protected] ~]# script.sh /mnt/userfile

please give me userfle or password file

[[email protected] ~]# script.sh

please give me userfle or password file

 

 


以上是关于脚本练习:建立用户的主要内容,如果未能解决你的问题,请参考以下文章

shell脚本练习题 二(for循环)

shell练习

linuxshell:简单的shell脚本练习

Linux的shell脚本random相关应用和批量修改建立练习

shell脚本进阶练习题---理解和练习

小脚本练习