How do i use the case statements in bash shell scripts?



  • Case statements are another type of conditional based on the expression.

    The structure is:

    case expression in 
     option1)  
      action 
     ;; 
     option2) 
      action 
     ;; 
     *) 
      action
     ;; 
    esac 
    

    Let's put it into action! The ;; is the end of action terminator. The * matches anything other than the options.

    $ cat caseofwine.sh 
    case "$1" in
    wine)
      echo "Have you tried our new vintage!"
      ;;
    beer)
      echo "Let's have a knees up!"
      ;;
    *)
      echo "Sorry, the party has been cancelled!"
      ;;
    esac
    

    Running the script.

    $ ./caseofwine.sh beer
    Let's have a knees up!
    $ ./caseofwine.sh wine
    Have you tried our new vintage!
    $ ./caseofwine.sh
    Sorry party has been cancelled!
    

Log in to reply
 

© Lightnetics 2024