提示输入值,直到按下 ENTER 键,值为空

提示输入值,直到按下 ENTER 键,值为空

我正在编写一个 bash 脚本来自动执行一些任务。这是我到目前为止所做的:

#!/usr/bin/env bash

PS3='Please enter your choice: '
options=("Create new group" "Add users to group" "Change directory ownership" "Change directory permissions" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Create new group")
            read -e -p "Enter the group name: " -i "www-pub" groupname
            groupadd groupname
            echo "You have added a new group: " groupname
            ;;
        "Add users to group")
            ## Here 
            ;;
        "Change directory ownership")
            read -e -p "Enter the group name: " -i "www-pub" "Enter the directory: " -i "/var/www/html" groupname directory
            chown -R root:groupname directory
            echo "You have changed the ownership for: " directory " to root:" groupname
            ;;
        "Change directory permissions")
            ## Actions for change directory permissions goes here
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

现在,在步骤 2 中,Add users to group我想向给定组添加多个用户。因此:

  • 我可以使用groupname步骤 1 中先前询问的内容吗,还是应该询问“groupname始终”?
  • 我需要通过运行此命令请求多个用户将其添加到组中:usermod -a -G groupname username,我如何请求他们直到值为空?

例如:

Add users to group
Enter the group name: www-pub
Enter user: user1
user1 added to www-pub
Enter user: user2
user2 added to www-pub
Enter user: (none hit ENTER without values)
Return to the main menu

有人能帮我构建这个代码块吗?

答案1

以下是一种方法:

    "Add users to group")
        read -e -p "Enter the group name: " -i "www-pub" groupname
        loop=true          # "true" is a command
        while $loop; do    # the "$loop" command is executed
            read -p "enter username: " username
            if [[ -z $username ]]; then
                loop=false # this command returns a fail status, and
                           # will break the while loop
            else
                # add user to group
            fi
        done
        ;;

更简洁的方式:

        while true; do
            read -p "enter username: " username
            [[ -z $username ]] && break
            # add user
        done

相关内容