管理者がスクリプトを実行するとループを実行しようとしていますが、追加するユーザーの数を尋ねるメッセージが表示され、管理者が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