我试图创建一个用户创建者脚本,我一直卡住。我刚开始学习bash shell脚本,所以我不是很好。以下是我的剧本:
#!/bin/bash
clear
echo "Welcome to"
echo "USER CREATOR"
echo "How many user accounts would you like to create?"
read num
echo "What would you like the username prefix to be? (e.g. 'Student' (Student01, Student02, Student03...) or 'User' (User01, User02, User03...)"
read prefix
declare -i maxaccounts=0
declare -i accountnum=1
zero="0"
while [ $num -gt $maxaccounts ]
do
if [ $accountnum -lt 10 ]
then
username=${prefix}${zero}${accountnum}
else
username=${prefix}${accountnum}
fi
if test -d /home/$username; then
accountnum=$accountnum+1
maxaccounts=$maxaccounts+1
else
useradd $username
accountnum=$accountnum+1
maxaccounts=$maxaccounts+1
fi
done
现在,它创建的用户帐户刚刚好...但由于某种原因,我不能弄清楚,它实际上并没有检查用户名是否存在,如果存在就跳过它。我能做什么?**(我也使用Centos虚拟机作为参考)
下面是我查看的其他一些论坛和网站,试图找出如何编写此代码:superuser: find-out-if-user-name-exists
stackoverflow: check-whether-a-user-exists?
stackoverflow: bash-script-to-validate-the-existence-of-user-name-in-etc-passwd
stackoverflow: how-would-i-check-if-user-exists-in-a-bash-script-and-re-ask-for-new-user-if-use
sslhow: check-user-shell-in-linux
unix.stackexchange: check-if-user-exist-in-etc-passwd-if-exist-create-new-one-with-prefix
baeldung: user-exists-check
更新
我想明白了我添加了maxaccounts=$maxaccounts+1
变量,以便在帐户未创建时也增加,因此它只是跳过创建新帐户,因为代码告诉它它已经在循环中创建了帐户。下面是我的最终代码:
#!/bin/bash
clear
echo "Welcome to"
echo "USER CREATOR"
echo "How many user accounts would you like to create?"
read num
echo "What would you like the username prefix to be? (e.g. 'Student' (Student01, Student02, Student03...) or 'User' (User01, User02, User03...)"
read prefix
declare -i maxaccounts=0
declare -i accountnum=1
zero="0"
while [ $num -gt $maxaccounts ]
do
if [ $accountnum -lt 10 ]
then
username=${prefix}${zero}${accountnum}
else
username=${prefix}${accountnum}
fi
if id -u $username &>/dev/null; then
accountnum=$accountnum+1
else
useradd $username
accountnum=$accountnum+1
maxaccounts=$maxaccounts+1
fi
done
1条答案
按热度按时间u1ehiz5o1#
就像这样:
或者只是:
备注
可以将
id
替换为