≡ Menu

5 Bash Case Statement Examples

Bash shell case statement is similar to switch statement in C. It can be used to test simple values like integers and characters.

Case statement is not a loop, it doesn’t execute a block of code for n number of times. Instead, bash shell checks the condition, and controls the flow of the program.

In this article let us review the bash case command with 5 practical examples.

The case construct in bash shell allows us to test strings against patterns that can contain wild card characters. Bash case statement is the simplest form of the bash if-then-else statement.

Syntax of bash case statement.

case expression in
    pattern1 )
        statements ;;
    pattern2 )
        statements ;;
    ...
esac

Following are the key points of bash case statements:

  • Case statement first expands the expression and tries to match it against each pattern.
  • When a match is found all of the associated statements until the double semicolon (;;) are executed.
  • After the first match, case terminates with the exit status of the last command that was executed.
  • If there is no match, exit status of case is zero.

Bash Case Example 1. Sending Signal to a Process

The following script accepts the signal number and process id as it’s arguments, and sends the signal to a given process id using signal name.

This script is to demonstrate the usage of the case statement.

$ cat signal.sh
#!/bin/bash

if [ $# -lt 2 ]
then
        echo "Usage : $0 Signalnumber PID"
        exit
fi

case "$1" in

1)  echo "Sending SIGHUP signal"
    kill -SIGHUP $2
    ;;
2)  echo  "Sending SIGINT signal"
    kill -SIGINT $2
    ;;
3)  echo  "Sending SIGQUIT signal"
    kill -SIGQUIT $2
    ;;
9) echo  "Sending SIGKILL signal"
   kill -SIGKILL $2
   ;;
*) echo "Signal number $1 is not processed"
   ;;
esac

In the above example:

  • $1 and $2 are the signal number and process id respectively.
  • Using kill command, it sends the corresponding signal to the given process id.
  • It executes the sleep command for a number of seconds.
  • The optional last comparison *) is a default case and that matches anything.

Usage of the above shell script: Find out the process id of the sleep command and send kill signal to that process id to kill the process.

$ sleep 1000

$ ps -a | grep sleep
23277 pts/2    00:00:00 sleep

$ ./signal.sh 9 23277
Sending SIGKILL signal

$ sleep 1000
Killed

Also, refer to our earlier kill article – 4 methods to kill a process.

Bash Case Example. 2. Pattern Match in a File

This example prints the number of lines,number of words and delete the lines that matches the given pattern.

$ cat fileop.sh
#!/bin/bash

# Check 3 arguments are given #
if [ $# -lt 3 ]
then
        echo "Usage : $0 option pattern filename"
        exit
fi

# Check the given file is exist #
if [ ! -f $3 ]
then
        echo "Filename given \"$3\" doesn't exist"
        exit
fi

case "$1" in

# Count number of lines matches
-i) echo "Number of lines matches with the pattern $2 :"
    grep -c -i $2 $3
    ;;
# Count number of words matches
-c) echo "Number of words matches with the pattern $2 :"
    grep -o -i $2 $3 | wc -l
    ;;
# print all the matched lines
-p) echo "Lines matches with the pattern $2 :"
    grep -i $2 $3
    ;;
# Delete all the lines matches with the pattern
-d) echo "After deleting the lines matches with the pattern $2 :"
    sed -n "/$2/!p" $3
    ;;
*) echo "Invalid option"
   ;;
esac

Execution of the above script is shown below.

$ cat text
Vim is a text editor released by Bram Moolenaar in 1991 for the Amiga computer.
The name "Vim" is an acronym for "Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code.
Although Vim was originally released for the Amiga, Vim has since been developed to be cross-platform, supporting many other platforms.
It is the most popular editor amongst Linux Journal readers.

Bash case regex output. After deleting the lines matches with the pattern Vim:

$ ./fileop.sh  -d Vim text
It is the most popular editor amongst Linux Journal readers.

Also, refer to our earlier article on Bash ~ expansaion and { } expansion.

Bash Case Example 3. Find File type from the Extension

This example prints type of a file (text, Csource, etc) based on the extension of the filename.

$ cat filetype.sh
#!/bin/bash
for filename in $(ls)
do
	# Take extension available in a filename
        ext=${filename##*\.}
        case "$ext" in
        c) echo "$filename : C source file"
           ;;
        o) echo "$filename : Object file"
           ;;
        sh) echo "$filename : Shell script"
            ;;
        txt) echo "$filename : Text file"
             ;;
        *) echo " $filename : Not processed"
           ;;
esac
done

$ ./filetype.sh
a.c : C source file
b.c : C source file
c1.txt : Text file
fileop.sh : Shell script
obj.o : Object file
text : Not processed
t.o : Object file

Bash Case Example 4. Prompt User with Yes or No

In most of the software installation, during license agreement, it will ask yes or no input from user. The following code snippet is one of the way to get the yes or no input from user.

$ cat yorno.sh
#!/bin/bash

echo -n "Do you agree with this? [yes or no]: "
read yno
case $yno in

        [yY] | [yY][Ee][Ss] )
                echo "Agreed"
                ;;

        [nN] | [n|N][O|o] )
                echo "Not agreed, you can't proceed the installation";
                exit 1
                ;;
        *) echo "Invalid input"
            ;;
esac

$ ./yorno.sh
Do you agree with this? [yes or no]: YES
Agreed

If there are several patterns separated by pipe characters, the expression can match any of them in order for the associated statements to be run. The patterns are checked in order until a match is found; if none is found, nothing happens.

Also, refer to our earlier 15 bash array examples article.

Bash Case Example 5. Startup script

Startup scripts in the /etc/init.d directory uses the case statement to start and stop the application.

You can use any kind of patterns, but its always recommended to use case statement, when you’re testing on values of primitives. (ie. integers or characters).

$ cat startpcapp
#!/bin/bash

case "$1" in
'start')
echo "Starting application"
/usr/bin/startpc
;;
'stop')
echo "Stopping application"
/usr/bin/stoppc
;;
'restart')
echo "Usage: $0 [start|stop]"
;;
esac

$ ./startpcapp start
Starting application
/usr/bin/startpc started

Recommended Reading

Bash 101 Hacks, by Ramesh Natarajan. I spend most of my time on Linux environment. So, naturally I’m a huge fan of Bash command line and shell scripting. 15 years back, when I was working on different flavors of *nix, I used to write lot of code on C shell and Korn shell. Later years, when I started working on Linux as system administrator, I pretty much automated every possible task using Bash shell scripting. Based on my Bash experience, I’ve written Bash 101 Hacks eBook that contains 101 practical examples on both Bash command line and shell scripting. If you’ve been thinking about mastering Bash, do yourself a favor and read this book, which will help you take control of your Bash command line and shell scripting.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Chris F.A. Johnson July 13, 2010, 7:42 am

    > case expression in

    The first argument to case is NOT an expression it is a string (or ‘word’, to quote the bash man page).

    > for filename in $(ls)

    Not only is ‘ls’ unnecessary, but it will break the script if any filenames contain whitespace or other pathological characters.

  • SilversleevesX August 2, 2010, 8:21 am

    Your example 4 (file type by extension) makes no provision for when an item in the folder happens to be a directory. I suggest this little conditional tweak to keep the script (and folks who use it to learn case/esac statements) from getting confused.

    regordir=$(stat -c %F $filename)
    if [[ $regordir != “directory” ]];
    then…
    (your list of file types and labels here)…
    fi
    Test your own out line by line with this series of one-liners and variable setters in a terminal/console:

    >> filename=”sandwich.txt”
    >> regordir=$(stat -c %F $filename)
    >> if [[ $regoderdir != “directory” ]]; then echo “I am not a folder “‘!’; else echo “Well, I guess I AM a folder, after all.”;fi

    A mere suggestion. Take what you like and leave the rest.

    Cheers,

    BZT

  • Brian C July 28, 2011, 1:56 pm

    Thanks for the tips.

    In example 4 there appears to be a typo. The vertical bar doesn’t belong when checking the “NO”, “no”, “No”, or “nO”
    I.E. This: [nN] | [n|N][O|o] ) Should be this: [nN] | [nN][Oo] )

  • s kumar September 1, 2011, 12:35 am

    1. Give two amount find the %?\
    2.Two convert centigrade to Fahrenheit
    3. Calculate are of a circle
    all above que. using by the shell programming

  • shweta October 22, 2012, 10:51 pm

    #!/bin/bash
    echo “enter the value”
    read a
    case $a in
    1) echo ” 1 ” ;&
    2) echo ” 2 ” ;&
    3) echo ” 3 ” ;;&
    4) echo ” 4 ” ;;
    5) echo ” 5 ” ;&
    esac

    i m a beginner in Shell Scripting , anybody can explain me, how these “;;&” , “;&” , “;;” terminator different from each other and how they work?

  • Chris F.A. Johnson October 22, 2012, 11:23 pm

    From the bash man page:

    Using ;& in place of ;; causes execution to continue with the list associated with the next set of patterns. Using ;;& in place of ;; causes the shell to test the next pattern list in the statement, if any, and execute any associated list on a successful match. The exit status is zero if no pattern matches. Otherwise, it is the exit status of the last command executed in list.

  • shweta October 31, 2012, 9:19 am

    @ Chris F.A. Johnson, thanx… ,i have one more confusion….. can u help

    if test $# = 3
    then
    case $2 in
    /) z=$(($1/$3));;
    x|X) z=$(($1*$3));;
    +) z=$(($1+$3));;
    -) z=$(($1-$3));;
    *) echo “warning – $2 invalid operator, pls use X or x”;;
    esac
    echo “$1 $2 $3 = $z”
    else
    echo “Pls Enter 3 values”
    fi
    ./Math.sh 3 * 33
    output
    Pls Enter 3 values

    I m not able 2 figure it out why this output, i m expecting ” “warning – $2 invalid operator, pls use X or x”

  • Chris F.A. Johnson October 31, 2012, 11:51 am

    Escape the asterisk or it will be expanded.

  • Ashish July 28, 2013, 11:32 pm

    Below is the content of file1.txt

    Dept Coll Score Grade
    ECE AIHT 90 A+
    CSC SSN 86 B
    MEC AVIT 88 B+
    EEE PSN 84 C

    Write one shell script for below requirement
    a. Get the column name as input during runtime (Dept of Coll or Score or Grade)
    Example…
    If you enter Coll in input during runtime, output should be as
    AIHT
    SSN
    AVIT
    PSN
    If you enter Dept in during runtime, output should be as
    ECE
    CSC
    MEC
    EEE

    b. If you enter invalid column name script should throw error

    Try doing it with, if or case statement and awk or grep commands.

  • Dinesh Kumar July 29, 2014, 5:48 am

    Hi,
    Thank you for all the amazing stuff on this website.

    For the example 4, is there any reason why we are not using the ‘shopt’ s (shopt -s nocasematch)?
    We could be setting ignore case and then unset it back. Is there any reason why this has to be avoided, because i usually use it in my little scripts.

    Thanks in advance.

  • KHALIQ February 8, 2015, 3:37 pm

    In a unix directory there are five applications and qa,init,prod when i run a start.sh it should pick up whatever env I give .can any one write the script and sendit to my mail please .with unix case statement..

  • damu February 21, 2017, 5:00 pm

    Awesome! First time created switch case statement in bash to symlink proper .env file based on `hostname`. Thank you.