While实现批量用户创建

While实现批量用户创建

一、创建用户文件

[root@localhost script]# cat username.txt 
user1
user2
user3
user4
user5

二、脚本案例

#!/bin/bash
#create user by While
#v1.0 itwangqiang 2020-12-28

while read user
do
        id $user &> /dev/null
        if [ $? -eq 0 ];then
                echo "The $user is exists"
        else
                useradd $user
                echo "create $user is successful!"
        fi
done < $1

三、执行

[root@localhost script]# ./created.sh username.txt 
create user1 is successful!
create user2 is successful!
create user3 is successful!
create user4 is successful!
create user5 is successful!

四、创建用户密码文件

[root@localhost script]# cat username.txt 
user1	123
user2	456
user3	789
user4	012
user5	345

五、脚本案例

  • 如果想要对文件逐行处理、逐行循环,首选 while 循环语句
#!/bin/bash
#create user by While
#v1.0 itwangqiang 2020-12-28

#while是以"回车"作为分隔,所有不需要重定义分隔符
while read line
do
        user=`echo $line | awk '{print $1}'`
        pass=`echo $line | awk '{print $2}'`
        id $user &> /dev/null
        if [ $? -eq 0 ];then
                echo "The $user is exists"
        else
                useradd $user
                echo "$pass" | passwd --stdin $user &> /dev/null
                if [ $? -eq 0 ];then
                        echo "create $user is successful!"
                fi
        fi
done < $1

六、用户文本中出现空行

[root@localhost script]# cat username.txt 
user1	123
user2	456

user3	789
user4	012

user5	345

七、脚本案例

#!/bin/bash
#create user by While
#v1.0 itwangqiang 2020-12-28

#while是以"回车"作为分隔,所有不需要重定义分隔符
while read line
do
        if [ ${#line} -eq 0 ];then
                echo "This is null line"
                continue
        fi
        user=`echo $line | awk '{print $1}'`
        pass=`echo $line | awk '{print $2}'`
        id $user &> /dev/null
        if [ $? -eq 0 ];then
                echo "The $user is exists"
        else
                useradd $user
                echo "$pass" | passwd --stdin $user &> /dev/null
                if [ $? -eq 0 ];then
                        echo "create $user is successful!"
                fi
        fi
done < $1
wait
echo "All is ok!!!!!!!!!"

八、until循环

Shell循环: while until
循环次数不一定是固定的
可以固定
可以不固定

1、while语句结构
while条件测试
do
      循环体
done
==当条件测试成立(条件测试为真) ,执行循环体

2、until语法结构
until条件测试
do
      循环体
done
==当条件测试成立(条件测试为假),执行 循环体
  • 脚本案例
1、while循环(当条件为真,则执行循环体)
#!/bin/bash

ip=192.168.121.17

while ping -c1 $ip &> /dev/null
do
        sleep 1
done
echo "$ip is dowm"



2、until循环(条件为假,则执行循环体)
#!/bin/bash

ip=192.168.121.17

until ping -c1 $ip &> /dev/null
do
        sleep 1
done
echo "$ip is up"
posted @ 2020-12-28 21:47  廿九九  阅读(246)  评论(0)    收藏  举报