Module-7 How to use Case statement in bash scripting

Table of contents

Introduction

Case statement : Case statement can be used in place to avoid writing complex nested if conditionals if we have many different conditional checks. Using case statement we can select a section of the code to execute after matching a pattern from the user inputs or other variable 

In this article we will be covering details on how to use the case statement in bash  

Syntax for case statement

It starts with the expression that can be also feeded through user inputs or other variables , then that is checked in the different pattern sections for example pattern_one , two etc , then if it matches that section it executes that code block and exits the case section . Also note the last pattern match which is a wildcard match which matches all the other inputs , so that we can prompt the user or throw an output to advise to input correct values 

case <expression> in

  pattern_one)
    bash-statements
    ;;

  pattern_two)
    bash-statements
    ;;

  *)
    bash-statements
    ;;
esac

Practical example on case statement

In this example script  , we are prompting the user to input a username , then that username is checked against various patterns defined in the case section and executes the code block based on that . Also in the pattern matches we can match multiple different pattern in the pattern subsection using “|”

#script 
[root@discoveringsystems case-statement]# cat case-statement
#!/bin/bash

read -p " enter the username : " username

case $username in

  Alice | alice)
    echo "Welcome Alice ! you role is network admin "
    ;;

  Bob | bob)
    echo "Welcome Bob ! your role is network operator "
    ;;

  Charlie | charlie)
    echo " Welcome Charlie ! your role is general operator "
    ;;

  *)
    echo " Entered value is incorrect , please re-enter the correct value "
    ;;

esac

We can see that when the script is executed and various inputs are provided , the code block execution was based on that 

#script execution with various inputs 
[root@discoveringsystems case-statement]# ./case-statement
 enter the username : alice
Welcome Alice ! you role is network admin

[root@discoveringsystems case-statement]# ./case-statement
 enter the username : alex
 Entered value is incorrect , please re-enter the correct value
[root@discoveringsystems case-statement]#

Leave a Comment

Your email address will not be published. Required fields are marked *