admin 管理员组文章数量: 1086019
shell脚本
大家好,我是沐风,互联网老辛的助理,今天由我分享shell脚本之创建用户的4种思路。
这里只是抛砖引玉,希望你看完之后能够用更多种方法实现,集思广益,用老辛讲的 【穷举法】反复练习。
需求描述:
写一个脚本,创建10个用户,以utest开头,比如utest1 utest2
创建完用户后直接配置密码,密码和用户名相同
脚本创建完用户和密码之后,最终展示一共增加了几个用户,分别是哪些用户?
思路一:
#!/bin/bash
total1=`cat /etc/passwd |wc -l`
for num in {1..10}
do
useradd utest$num
echo utest$num |passwd --stdin utest$num
donetotal2=`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)
do
useradd user$i
echo user$i | passwd --stdin user$i
if ! id user$i &>/dev/null
thenecho "error:user$i未创建成功!"
elseecho "user$i创建成功!"
fi
done
SD=$(cat /etc/passwd | grep user | awk -F ":" '{print $1}')
echo 总共增加了 $i 个用户!
echo -e “分别为:$SD”
思路三(翟同学提供的思路):
#!/bin/bash
userNum=0
for num in {1..6}
douseradd user${num}echo user${num}|passwd --stdin user${num}id user${num}if [ $? -eq 0 ];thenlet userNum+=1echo user${num} >>users.txtecho "user${num}用户创建成功!"elseecho "user${num}用户创建失败!!!"fi
done
printf "总共创建了${userNum}个用户,分别是:%s\t%s\t%s\t%s\t%s\t%s\n" $(cat users.txt)
思路四(徐同学提供的思路)
#!/bin/bash
num=0
for j in user{1..6};do userdel -r $j >/dev/null;done
for i in user{1..6}do
useradd $i
if [ $? -eq 0 ];then
echo “$i用户添加成功”
let num++
echo $i | passwd --stdin $i >/dev/null
fi
done
echo " 一共添加了 $num个用户"
穷举法就是在一个脚本上,去使用多种方法解决,不断尝试去优化同一个脚本, 把脚本模块化之后,内化成自己的。
反复练习是成功的保证
本文标签: shell脚本
版权声明:本文标题:shell脚本 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1686558729a10162.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论