ループは、ユーザーが一意の値を入力するまで引き続き値を求めます。

ループは、ユーザーが一意の値を入力するまで引き続き値を求めます。

LVM関連タスクを自動化するためのスクリプトを作成しています。スクリプトでは、ユーザーがVG名を入力することを望み、名前は一意である必要があります。ユーザーがシステムにすでに存在するVG名を入力したときに、前に進まずに一意になるまでVG名を要求するようにループを作成するにはどうすればよいですか?

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注:どういう意味なのかわかりません。

おすすめ記事