![对函数执行循环](https://linux22.com/image/174052/%E5%AF%B9%E5%87%BD%E6%95%B0%E6%89%A7%E8%A1%8C%E5%BE%AA%E7%8E%AF.png)
我试图在管理员运行脚本时执行一个循环,它会提示他要添加多少个用户,如果他输入 2,我希望在要求用户名和密码的部分运行一个循环例如,如果管理员输入 5,则会询问他用户名和密码 5 次。这可能吗,请告诉我。这是一个课程,我是脚本新手,所以它看起来可能很可怕
#!/bin/bash
read -r -p "Hello Titan, How many users would you like to add to the mainframe : " input
if [[ $input =~ ^[1-9]$ ]] ;
then
echo "Thank you Titan, Now Adding $input User(s) to the mainframe"
**if [[ $input == 1 ]] ; then
read -p "Enter Username : " username
read -p "Enter password : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ] ; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p "$pass" "$username"
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Can not add users"
fi**
else
echo "Amount of users invalid"
fi
答案1
只需将要重复的代码移至函数中即可:
#!/bin/bash
add_user () {
if [[ $input == 1 ]] ; then
read -p "Enter Username : " username
read -p "Enter password : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ] ; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p "$pass" "$username"
[ $? -eq 0 ] && echo "User has been added to system!" ||
echo "Failed to add a user!"
fi
else
echo "Can not add users"
fi
}
read -r -p "Hello Titan, How many users would you like to add to the mainframe : " input
if [[ $input =~ ^[1-9]$ ]] ; then
echo "Thank you Titan, Now Adding $input User(s) to the mainframe"
for((i=0;i<input;i++)); do
add_user
done
else
echo "Amount of users invalid"
fi
答案2
在您的帮助下,我能够获得正确的编码,谢谢 Hauke!
read -r -p "Hello Titan, How many users would you like to add to the mainframe : " input
if [[ $input =~ ^[1-9]$ ]] ; then
echo "Thank you Titan, Now Adding $input User(s) to the mainframe"
for ((i=0; i<input; i++)) ; do
read -p "Enter Username : " username
read -p "Enter password : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ] ; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p "$pass" "$username"
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
done
else
echo "Amount of users invalid"
fi