循环不断询问该值,直到用户输入唯一值

循环不断询问该值,直到用户输入唯一值

我正在为有关 LVM 的自动化任务创建一个脚本。在脚本中,我希望用户输入 VG 名称,并且它必须是唯一的。如何创建一个循环,以便在用户输入系统中已存在的 VG 名称时,它不会继续前进并继续询问 VGname 直到其唯一。

我用于创建 VG 的函数如下:

vg_create(){
        printf "\n"
        printf "The list of volume groups in the system are: \n"
        vgs | tail -n+2 | awk '{print $1}'

        printf "\nThe list of Physical Volumes available in the OS are as follows: \n"
        view_pvs  ## Calling another function
        printf "\n"
        printf "[USAGE]: vgcreate vgname pvname\n"
        read -p "Enter the name of the volume group to be created: " vgname
        printf "\n"

        vg_match=`pvs | tail -n+2 | awk '{print $2}' | grep -cw $vgname`

                if [ $vg_match -eq 1 ]; then
                   echo -e "${vgname} already exists. Kindly enter new name.\n"
                else
                   echo -e "${vgname} doesn't exist in system and will be created.\n"
                fi
        read -p "Enter the name of the physical volume on which volume group to be created: " pv2_name
        printf "\n"
        vgcreate ${vgname} ${pv2_name}

        printf "\n"
        printf "The new list of volume groups in the system are: \n"
        vgs | tail -n+2 | awk '{print $1}'
}

答案1

一般来说:

# loop until we get correct input from user
while true; do
    # get input from user

    # check input

    # break if ok
done

或者,更具体一点:

# loop until we get correct input from user
while true; do
    read -r -p "Give your input: " answer

    # check $answer, break out of loop if ok, otherwise try again

    if pvs | awk 'NR > 2 {print $2}' | grep -qw -e "$answer"; then
        printf '%s already exists\n' "$answer" >&2
    else
        break
    fi
done

注意:我不知道pvs是什么意思。

答案2

以下是检查 VG 是否存在的两种不同方法:

  1. 尝试直接读取VG vgs --readonly "$vgname";如果该命令成功,则 VG 已存在。
  2. 如果 vgname 在 的输出中列出vgs,则 VG 已存在。

请注意,第二种方法特别vgs要求不是打印标题并仅打印 VG 名称字段。该名称(在我的系统上)通常打印有前导空格和尾随空格,这就是表达式grep看起来如此的原因。

read -p "Enter the name of the volume group to be created: " vgname
while vgs --readonly "$vgname" > /dev/null 2>&1
do
  read -p "Enter the name of the volume group to be created: " vgname
  if vgs --noheadings -o vg_name | grep -q "^ *${vgname} *\$"
  then
    printf "That VG name is already taken; try something else\n" >&2
  fi
done

相关内容