我正在尝试编写一个创建用户的 shell 脚本,然后询问用户想要将他们刚刚创建的用户分配给哪个组名,最后需要询问用户是否想要创建另一个用户。
我不断收到第 21 行:在意外标记“else”附近出现语法错误第 21 行“else”
#!/usr/bin/env bash
anotherUser() {
read -p "Do you want to add another user? [y/n] yn"
if [[ $yn = *[yY]* ]]; then
checkUser
fi
exit
}
checkUser() {
while :
do
read -p "Enter username you would like to generate: " userName
read -s -p "Enter password : " userPass
if id "$userName" >/dev/null; then
echo "Sorry user exists"
anotherUser
else
echo adduser "$userName"
printf "User %s has been added\n" "$userName"
else
read -p "Enter group you want to assign user to: " userGroups
useradd -G "userGroups" "$userName" &&
printf "User %s has been added\n" "$userName"
fi
break
done
exit
fi
done
}
checkUser
答案1
这个怎么样:
#!/usr/bin/env bash
checkUser() {
while true; do
read -p "Enter username you would like to generate: " userName
if id "$userName" >/dev/null 2&>1; then
echo "Sorry user exists"
else
read -s -p "Enter password : " userPass
echo adduser "$userName"
printf "User %s has been added\n" "$userName"
read -p "Enter group you want to assign user to: " userGroups
useradd -G "userGroups" "$userName" &&
printf "User has been added to group %s\n" "$userGroups"
fi
read -p "Do you want to add another user? [y/n] " yn
if [[ $yn = *[nN]* ]]; then
break
fi
done
}
checkUser
答案2
这应该有效:
#!/bin/bash
anotherUser() {
read -p -r "Do you want to add another user? [y/n] yn" yn
if [[ $yn = \*[yY]\* ]]; then
checkUser
fi
return 1
}
checkUser() {
while :
do
read -p -r "Enter username you would like to generate: " userName
if id "$userName" >/dev/null; then
echo "Sorry user exists"
anotherUser
else
echo adduser "$userName"
printf "User %s has been added\n" "$userName"
read -p -r "Enter group you want to assign user to: " userGroups
useradd -G "$userGroups" "$userName" &&
printf "User %s has been added\n" "$userName"
return 0
fi
done
}
checkUser