允许用户仅选择一组显示的 ID

Allow user to choose only set of displayed IDs

我真的不知道这叫什么所以是的,基本上我想让用户 select 只显示 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

allowed=( $(mysql -D snipeit -e "SELECT id AS ID, name AS Name FROM categories WHERE category_type='accessory';" | awk 'NR>=4{print }') )

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

你可以尝试使用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

我用

解决了这个问题
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 的帮助!