0

I am working on a script to back up my CouchPotatoServer, but I'm having problems.

Here is the code I am having problems with:

select OPTION in Backup Restore Finish; do
    echo "You choose $OPTION CouchPotatoServer settings";
    case $OPTION in
        Backup)
            echo "Backing up settings file to $CPBPATH:";
            cp $CPSPATH/settings.conf $CPBPATH/settings-"$(date +%Y%m%d-%H%M)".bak ;
            echo "Done!"
            break
            ;;
        Restore)
            echo "Please choose a backup to restore settings" ;
            AVAILABLEFILES="($(find $CPBPATH -maxdepth 1 -print0 | xargs -0))"
            select FILE in $AVAILABLEFILES; do
                cp "$FILE" $CPSPATH/settings.conf ;
                echo "restored $FILE"
                break
                ;;
done

The problem is that after the user chooses one option and the code is executed, it keeps waiting for a new selection, but I want it to exit. How can I do that?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

1 Answers1

1

break exits a loop, but you have nested loops and get stuck in the outer one. break actually takes an argument to specify how many enclosing loops you want to exit, so when you replace your break with break 2, you'll also exit the outer select loop.

Here is a little script to demonstrate the different break levels in select statements:

#!/bin/bash

PS3="Outer selection: "
select option1 in outer1 outer2 ; do
    echo "option1 is $option1"
    PS3="Inner selection: "
    case "$option1" in
        outer1)
            select option2 in inner1 inner2; do
                echo "option2 is $option2, issuing 'break'"
                PS3="Outer selection: "
                break
            done
            ;;
        outer2)
            select option2 in inner3 inner4; do
                echo "option2 is $option2, issuing 'break 2'"
                break 2
            done
            ;;
    esac
done

PS3 is the prompt shown when using the select statement. As long as the outer option is outer1, you'll loop back to the outer select because only a single break is issued; if you select outer2, you'll exit the program with break 2.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116