shell脚本-创建用户的4种思路
大家好,我是沐风,互联网老辛的助理,今天由我分享shell脚本之创建用户的4种思路。
这里只是抛砖引玉,希望你看完之后能够用更多种方法实现,集思广益,用老辛讲的 【穷举法】反复练习。
需求描述:
写一个脚本,创建10个用户,以utest开头,比如utest1 utest2
创建完用户后直接配置密码,密码和用户名相同
脚本创建完用户和密码之后,最终展示一共增加了几个用户,分别是哪些用户?
思路一:
#!/bin/bashtotal1=`cat /etc/passwd |wc -l`for num in {1..10}douseradd utest$numecho utest$num |passwd --stdin utest$numdonetotal2=`cat /etc/passwd |wc -l`total=$(($total2 - $total1))echo "新增加的用户数一共有$total个"echo "分别是:"head -n $total /etc/passwd
思路二(郑同学提供的思路):
cat useradd2.sh #!/bin/bashfor i in $(seq 10)douseradd user$iecho user$i | passwd --stdin user$iif ! id user$i &>/dev/nullthen echo "error:user$i未创建成功!"else echo "user$i创建成功!"fidoneSD=$(cat /etc/passwd | grep user | awk -F ":" '{print $1}')echo 总共增加了 $i 个用户!echo -e “分别为:$SD”
思路三(翟同学提供的思路):
#!/bin/bashuserNum=0 for num in {1..6}do useradd user${num} echo user${num}|passwd --stdin user${num} id user${num} if [ $? -eq 0 ];then let userNum+=1 echo user${num} >>users.txt echo "user${num}用户创建成功!" else echo "user${num}用户创建失败!!!" fidoneprintf "总共创建了${userNum}个用户,分别是:%s\t%s\t%s\t%s\t%s\t%s\n" $(cat users.txt)
思路四(徐同学提供的思路)
#!/bin/bashnum=0for j in user{1..6};do userdel -r $j >/dev/null;donefor i in user{1..6}douseradd $iif [ $? -eq 0 ];thenecho “$i用户添加成功”let num++echo $i | passwd --stdin $i >/dev/nullfidoneecho " 一共添加了 $num个用户"
穷举法就是在一个脚本上,去使用多种方法解决,不断尝试去优化同一个脚本, 把脚本模块化之后,内化成自己的。
反复练习是成功的保证