向system-Shell脚本添加用户和组
我正在尝试编写一个简短的脚本,将用户添加到系统中,并通过在逗号后拆分字符串,向用户提供按用户名删除用户列表的选项向system-Shell脚本添加用户和组,shell,sh,Shell,Sh,我正在尝试编写一个简短的脚本,将用户添加到系统中,并通过在逗号后拆分字符串,向用户提供按用户名删除用户列表的选项 #!/bin/bash while [ x"$username" = x ]; do read -p "Please enter the username you wish to create : " username if id -u "$username" >/dev/null 2>&1; then echo "Use
#!/bin/bash
while [ x"$username" = x ]; do
read -p "Please enter the username you wish to create : " username
if id -u "$username" >/dev/null 2>&1; then
echo "User already exists"
username=""
fi
done
while [ x"$group" = x ]; do
read -p "Please enter the primary group. If group not exist, it will be created : " group
if id -g "$group" >/dev/null 2>&1; then
echo "Group exist"
else
groupadd "$group"
fi
done
read -p "Please enter bash [/bin/bash] : " bash
if [ x"$bash" = x ]; then
bash="/bin/bash"
fi
read -p "Please enter homedir [/home/$username] : " homedir
if [ x"$homedir" = x ]; then
homedir="/home/$username"
fi
read -p "Please confirm [y/n]" confirm
if [ "$confirm" = y ]; then
useradd -g "$group" -s $bash -d $homedir -m $username
fi
while [ "$retry" = y ]; do
retry="n"
read -p "Do you want to delete users. Enter their username separated by a comma:" users
if [ x"$users" = x ]; then
read -p "No user name inserted. Try again? [y/n]" retry
fi
done
IFS=', ' read -r -a array <<< "$users"
for user in "${array[@]}"
do
userdel -r "$user"
done
说到shell脚本,我是一个彻头彻尾的乞丐。你能不能也给我解释一下我哪里弄错了?
谢谢大家抽出时间!
检查代码时使用为什么您的脚本是双倍行距的?
[x$username=“x”]
引用的内容完全错误x
不需要被引用<代码>需要引用“$username”。在这里提问之前,先运行代码并修复它发现的内容。(坦率地说,[“$username”=”]
或[-z“$username”]
会更清晰)。@CharlesDuffy我已经更正了我的脚本@stark建议您应该删除不必要的额外行,缩进循环和条件表达式的内容,以使代码更具可读性$(cat/etc/passwd | cut-d:-f1)--请参阅和。(另外,作为一项规则,不要直接阅读/etc/passwd
或/etc/group
——根据nsswitch
的配置方式,您的系统上可能会有来自其他地方的用户;在Linux上,如果您使用getent passwd
和getent group
,无论您的操作系统配置的数据源是什么,这都会起作用。)红色,用于跟踪用户帐户)。
for i in $(cat /etc/passwd | cut -d: -f1); do
echo -n $i ": "
grep $i /etc/group | cut -d: -f1 | tr "\n" " "
echo
done