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
为者常成,行者常至
Give me five~!