albertone74 albertone74 - 1 month ago 7
Linux Question

Dialog: Show menu after option has been executed

I hope someone can help me out with my query.

I would like to achieve the same results as the code below but using dialog instead.

#!/bin/bash
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option3" "Quit")
select opt in "${options[@]}"
do
case $opt in
"Option 1")
sudo apt-get update
;;
"Option 2")
echo "you chose choice 2"
;;
"Option 3")
echo "you chose choice 3"
;;
"Quit")
break
;;
*) echo invalid option;;
esac
done


Please see below the code for dialog:

#!/bin/bash

HEIGHT=15
WIDTH=40
CHOICE_HEIGHT=4
BACKTITLE="Backtitle here"
TITLE="Title here"
MENU="Choose one of the following options:"

OPTIONS=(1 "Option 1"
2 "Option 2"
3 "Option 3")

CHOICE=$(dialog --clear \
--backtitle "$BACKTITLE" \
--title "$TITLE" \
--menu "$MENU" \
$HEIGHT $WIDTH $CHOICE_HEIGHT \
"${OPTIONS[@]}" \
2>&1 >/dev/tty)

clear
case $CHOICE in
1)
sudo apt-get update
;;
2)
echo "You chose Option 2"
;;
3)
echo "You chose Option 3"
;;
esac


Basically after selecting option 1 for example I would like to get prompted with the same menu again.

Many thanks in advance for your kind help.

Kind regards.

Answer

You can insert the dialog section into a while loop

#!/bin/bash

HEIGHT=15
WIDTH=40
CHOICE_HEIGHT=4
BACKTITLE="Backtitle here"
TITLE="Title here"
MENU="Choose one of the following options:"

OPTIONS=(1 "Option 1"
         2 "Option 2"
         3 "Option 3"
         4 "Quit")

while [ "$CHOICE" -ne 4 ]; do
    CHOICE=$(dialog --clear \
                    --backtitle "$BACKTITLE" \
                    --title "$TITLE" \
                    --menu "$MENU" \
                    $HEIGHT $WIDTH $CHOICE_HEIGHT \
                    "${OPTIONS[@]}" \
                    2>&1 >/dev/tty)

    clear
    case $CHOICE in
            1)
                sudo apt-get update
                ;;
            2)
                echo "You chose Option 2"
                ;;
            3)
                echo "You chose Option 3"
                ;;
    esac
done