我真的不知道这叫什么,所以是的,基本上我想让用户只选择显示的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
答案 0 :(得分:1)
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
答案 1 :(得分: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
答案 2 :(得分:0)
我用
解决了这个问题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的帮助!