2016-07-28 152 views
0

你好,我想自动设置我的服务器上的用户。所以我开始用这个简单的bashbash脚本中的命令变量

#! /bin/bash 

if [ $# -ne 2 ] 
then 
echo "Usage: $(basename $0) USERNAME PASSWORD" 
exit 1 
fi 
user_name=$1 
password_var=$2 

exec useradd -m $user_name 
usermod -s /bin/bash 
#echo "$2" | exec chpasswd $user_name --stdin 
usermod -aG www-data "${user_name}" 

我有问题的最后一行。我刚刚创建的用户未分配给组www-data。当我只使用最后一行和评论everthing其他和饲养我的一个用户到脚本我能够添加自己,有人可以解释我为什么这是致命的?

+3

'exec'永远不会返回 – Mat

回答

1
exec useradd -m $user_name 

替换当前的进程,即bash这里useradd -m $user_name
此外,我没有看到在这里使用exec的任何实际优势。

此外,随着Linux的密码可以有空格,我建议做

password_var="$2" #prevents word splitting 

随着一些错误检查,我的最终脚本会

password_var="$2" 
useradd -mp "$password_var" "$user_name" # You haven't used password 
if [ $? -ne 0 ] # checking the exit status of the last command 
then 
    echo "User creation failed" 
    exit 1 
else 
usermod -s /bin/bash "$user_name" #username missing in the original code 
usermod -aG www-data "$user_name" 
fi 
+0

是的,这是它,也要感谢清理工作;) – theDrifter