Why doesn't this loop the menu?

Solution 1:

The problem is in your while loop conditions. This line:

while [[ $menu_choice -ne 3 && $quit_program != "y" ]]

is saying "while menu_choice isn't 3 and quit_program isn't y, keep looping." The problem is that, if either of those conditions is no longer true, the while loop will end.

What you want is this:

while [[ $menu_choice -ne 3 || $quit_program != "y" ]]

using || instead of &&. This way, the while loop will continue to loop as long as either condition is true, instead of both.

Solution 2:

This simpler script should work for you

#!/bin/bash

menu_choice=0
quit_program=false

while [ $quit_program == false ]
do

    printf "1. Backup\n"
    printf "2. Display\n"
    printf "3. Exit\n\n"

    printf "Enter choice: \n"
    read menu_choice

    if [ $menu_choice -eq 3 ]
    then
        printf "Are you sure you want to quit? (y/n) "
        read ask
        if [ $ask == "y" ]
        then
            quit_program=true
        fi

    fi

done

printf "\nDone\n"

There's no need to keep checking the menu_choice, so that can be removed from the while loop check.

In my example above, I just set a boolean of quit_program which is checked in the loop. If the user chooses option 3, and then says "y" to the confirmation, then the boolean is set to true to kill the loop.

You can also go even further without checking a boolean with this:

#!/bin/bash

menu_choice=0

while true
do
    printf "1. Backup\n"
    printf "2. Display\n"
    printf "3. Exit\n\n"

    printf "Enter choice: \n"
    read menu_choice

    if [ $menu_choice -eq 3 ]
    then
        printf "Are you sure you want to quit? (y/n) "
        read ask
        if [ $ask == "y" ]; then break; fi
    fi
done

printf "\nDone\n"

This second example accomplishes the same thing, but the while loop just runs without checking the boolean from before. The loop is broken with the break command instead.