我的脚本如何提示我需要创建的用户数量?

我的脚本如何提示我需要创建的用户数量?

我在 Linux 机器上有这个脚本:

#!/bin/bash
echo "Creating a user file using while loop"
Name=" "
Surname=" "

for ((i=1;i<6;i++)); do
    ((a=((i-1)%5)+1))

    echo "USER: $i"
    echo "_________________"
    echo "Enter first name"
    read Name
    echo "Enter surname"
    read Surname
    echo "Your name is $Name"
    echo "Your surname is $Surname"
done

我该如何修改它,以便它提示我输入要创建的用户数?

答案1

#!/bin/bash
echo "Creating a user file using while loop"
Name=" "
Surname=" "
echo -n "Enter the number of users to create: "
read no_of_users
for ((i=1;i<=no_of_users;i++)); do
        echo "_________________"
        echo "USER: $i"
        echo -n "Enter first name: "
        read Name
        echo -n "Enter surname: "
        read Surname
        echo "Your name is: $Name"
        echo "Your surname is: $Surname"
done

答案2

您可以在脚本顶部读取要创建的用户数量,然后在循环中使用该数字。

这是对脚本变体的建议,您可以另外在命令行上提供用户数量。如果您没有在命令行上给出数字,它将以交互方式询问该数字。不进行输入验证。

#!/bin/bash

nusers=$1
if [[ -z $nusers ]]; then
    read -p 'Number of users to add: ' nusers
fi

for (( i = 1; i <= nusers; ++i )); do
    read -p "User $i first name:  " name1
    read -p "User $i second name: " name2

    printf 'Hello %s %s\n' "$name1" "$name2"
done

测试:

$ ./script.sh
Number of users to add: 2
User 1 first name:  Apple
User 1 second name: Wonder
Hello Apple Wonder
User 2 first name:  Mini
User 2 second name: Uncle
Hello Mini Uncle
$ ./script.sh 2
User 1 first name:  Moped
User 1 second name: Runner
Hello Moped Runner
User 2 first name:  Tentative
User 2 second name: Luck
Hello Tentative Luck

相关内容