while循环创建用户(区别for)

while批量创建用户

vim while_create_user.sh

 1 #!/usr/bin/bash
 2 
 3 #while create user
 4 
 5 #v1.0 by xfeng
 6 
 7 while  read line
 8 
 9 do
10 
11   if [ ${#line} -eq 0 ];then    #变量的字符串长度
12 
13     echo "the line is null..."
14 
15     continue        #continue跳过本次循环,break跳过所有循环,exit直接终止程序
16 
17   fi
18 
19   user=`echo $line|awk '{print $1}'`
20 
21   pass=`echo $line|awk '{print $2}'`
22 
23   id $user &>/dev/null
24 
25   if [ $? -eq 0 ];then
26 
27     echo "user $user already exists"
28 
29   else
30 
31     useradd $user
32 
33     echo "$pass"|pass --stdin  $user &>/dev/null
34 
35     if [ $? -eq 0 ];then
36 
37       echo "$user is created...."
38 
39     fi
40 
41   fi
42 
43 done< $1      #while读取文件是按行读取,for读取文件默认是以空格或者tab键作为分隔符
44 
45 echo  "All is ok....."

continue跳过空行循环,继续执行后面的内容;break跳过本次循环及后面所有内容循环,执行循环以外的内容;exit跳过本次程序,退出shell。

cat a.txt

feng  123456

xiao 445566

sh -vx while_create_user.sh  a.txt

原文地址:https://www.cnblogs.com/xiaofeng666/p/12243346.html