【问题标题】:Allow user to choose only set of displayed IDs允许用户仅选择一组显示的 ID
【发布时间】:2016-07-14 06:56:39
【问题描述】:

我真的不知道这叫什么,是的,基本上我想让用户只选择显示的 ID(见图)。我正在考虑有一个变量并将这些数字保存为数组,但我不知道,因为我仍在学习 bash 脚本。谢谢!

我的脚本是这样的

read -p "Select accessory category below."
mysql -D snipeit -e "SELECT id AS ID, name AS Name FROM categories WHERE category_type='accessory';"
read -p "Accessory category: " accessoryCateg
if *(allow only 4, 5, 7, 8, 9, 10, 11, 12, 13, 14 to be selected)*
*inserts data into database*
else echo "Try again!"
fi

【问题讨论】:

    标签: linux bash shell centos7


    【解决方案1】:

    您可以尝试使用select 命令:

    echo "Select accessory category below."
    sample1=`mysql -D snipeit -e "SELECT id AS ID FROM categories WHERE category_type='accessory';"`
    options=(`echo $sample1 | cut -d ' ' -f2-`)
    
    PS3="Please select a category: "
    select accessoryCateg in "${options[@]}"
    do
    echo "selected $accessoryCateg"
    #inserts data into database
    break;
    done
    

    【讨论】:

    • 您的代码在下方显示选择配件类别。 1) 4 5 7 8 9 10 11 12 13 14 请选择一个类别:已选择4个
    • 哦,options=的那一行...需要更改,我已经编辑了我之前的帖子。
    【解决方案2】:
    allowed=( $(mysql -D snipeit -e "SELECT id AS ID, name AS Name FROM categories WHERE category_type='accessory';" | awk 'NR>=4{print $2}') )
    
    read -p "Accessory category: " accessoryCateg
    for item in "${allowed[@]}"
    do
      if [ "$item" -eq "$accessoryCateg" ]
      then
        #Insert Data to database
        found=1;
        break; #Don't need to continue.
      fi
    done
    if [ "$found" -ne 1 ]
    then
        echo "Not a valid category, Please try again"
    fi
    

    【讨论】:

    • 谢谢你,我会试试这个,如果它有效,我会回来报告
    • @PauloBernardo:谢谢,非常感谢
    • 我今天才注意到,我应该把完成放在哪里?在您的代码中,您有 2 个 done 但只有 1 个 do
    【解决方案3】:

    我解决了这个问题

    echo "Select accessory category below."
    mysql -D snipeit -e "SELECT id AS ID, name AS Name FROM categories WHERE category_type='accessory';"
    read -p "Accessory category: " userAccCateg
    varAccCateg=$(mysql -D snipeit -e "SELECT id FROM categories WHERE category_type='accessory';")
    accCateg=(`echo $varAccCateg | cut -d ' ' -f2-`)
    
    if [[ " ${accCateg[@]} " =~ " ${userAccCateg} " ]]; then
        echo "You have chosen $userAccCateg"
    else
        echo "Wrong choice!"
    fi
    

    结果是这样的

    感谢@zhliu03 和@sjsam 的帮助!

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 2016-08-15
      • 2015-09-01
      • 2018-06-27
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多