LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Trying to do nested case statement with great difficulties (https://www.linuxquestions.org/questions/linux-newbie-8/trying-to-do-nested-case-statement-with-great-difficulties-4175613174/)

fusion1275 09-03-2017 01:17 PM

Trying to do nested case statement with great difficulties
 
Hi all,

So I am trying build a quick bash script that will stop an application on 1 level of the case statement but inside it can bring down certain components of it separately but I am really fighting with it. The commands I want on the cmd line are the following:

Quote:

./script.sh start
./script.sh start comp
./script.sh stop
./script.sh stop comp
Code I have currently:

Code:

ACTION="$1"
OPTION="$2"

        case ${ACTION} in
                        start)
                                echo "starting the application"
                                ;;
                                               
                                case ${OPTION} in
                                        comp) echo "Starting app component"
                                        ;;
                                esac

                        stop)
                                echo "stopping the application"
                                ;;

esac

Please be gently as I did try and I am very much still learning how this all works.

Thanks for any help you can provide.

michaelk 09-03-2017 02:28 PM

One of those can't see the forest for the trees.

Code:

case ${ACTION} in
      start)
            echo "starting the application"
            ;;  <--- misplaced
                                               
            case ${OPTION} in
                  comp) echo "Starting app component"
                  ;;
            esac
            ;;  <--- should be here.

    stop)
        echo "stopping the application"
        ;;

esac

Using set -xv at the beginning of a script will help you debug your code.

jmgibson1981 09-04-2017 10:33 AM

you can also remove the static variables and put them directly in the case statement.

Code:

case "$1" in
  start)
    echo "Starting application"
    case "$2" in
      comp)
        echo "starting app component"
        ;;
    esac
    ;;
  stop)
    echo "stopping application"
    ;;
esac


MadeInGermany 09-05-2017 03:10 AM

Usually I do not further indent the parts that belong to the case-esac.
Also I put symmetric ( ) that is allowed in all Posix shells, avoids a problem with $( ) in bash-3 and has advantages in text editors.
Code:

case $ACTION in
(start)
    echo "starting the application"
    case $OPTION in
    (comp)
        echo "Starting app component"
    ;;
    esac
;;
(stop)
    echo "stopping the application"
;;
esac



All times are GMT -5. The time now is 09:49 PM.