#bash #scripting #menu #case
#bash #сценарии #меню #случай
Вопрос:
Эй, ребята, итак, я пытаюсь заставить это меню зацикливаться всякий раз, когда в операторе case делается неверный выбор, но мне трудно понять, к чему я должен перезванивать в моем цикле while, я попытался использовать *, поскольку это то, на что ссылается case как недопустимый выбор, но он ожидает операндкогда он видит это, поэтому я не уверен, как вызвать его обратно, ниже приведен код, любая помощь приветствуется.
#Main menu.
#Displays a greeting and waits 8 seconds before clearing the screen
echo "Hello and welcome to the group 97 project we hope you enjoy using our program!"
sleep 8s
clear
while [[ $option -eq "*" ]]
do
#Displays a list of options for the user to choose.
echo "Please select one of the folowing options."
echo -e "t0. Exit program"
echo -e "t1. Find the even multiples of any number."
echo -e "t2. Find the terms of any linear sequence given the rule Un=an b."
echo -e "t2. Find the numbers that can be expressed as the product of two nonnegative integers in succession and print them in increasing order."
#Reads the option selection from user and checks it against case for what to do.
read -n 1 option
case $option in
0)
exit ;;
1)
echo task1 ;;
2)
echo task2 ;;
3)
echo task3 ;;
*)
clear
echo "Invalid selection, please try again.";;
esac
done
Комментарии:
1. fwiw, хорошая привычка, с точки зрения удобства чтения, заключается в том, чтобы делать отступы в коде и использовать несколько пустых строк, чтобы разбить стену текста …
2. хорошо, спасибо за совет, я попробую начать делать это с этого момента
Ответ №1:
select
Реализация вашего меню:
#!/usr/bin/env bash
PS3='Please select one of the options: '
select _ in
'Exit program'
'Find the even multiples of any number.'
'Find the terms of any linear sequence given the rule Un=an b.'
'Find the numbers that can be expressed as the product of two nonnegative integers in succession and print them in increasing order.'
do
case $REPLY in
1) exit ;;
2) echo task1 ;;
3) echo task2 ;;
4) echo task3 ;;
*) echo 'Invalid selection, please try again.' ;;
esac
done
Ответ №2:
Не изобретайте встроенную select
команду
choices=(
"Exit program"
"Find the even multiples of any number."
"Find the terms of any linear sequence given the rule Un=an b."
"Find the numbers that can be expressed as the product of two nonnegative integers in succession and print them in increasing order."
)
PS3="Please select one of the options: "
select choice in "${choices[@]}"; do
case $choice in
"${choices[0]}") exit ;;
"${choices[1]}")
echo task1
break ;;
"${choices[2]}")
echo task2
break ;;
"${choices[3]}")
echo task3
break ;;
esac
done
Если вы хотите оставаться в меню до «Выхода», удалите разрывы.