5 Bash Case Statement Examples

来源:互联网 发布:黄光剑抄袭软件 编辑:程序博客网 时间:2024/06/15 19:15

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/bashif [ $# -lt 2 ]then        echo "Usage : $0 Signalnumber PID"        exitficase "$1" in1)  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 sleep23277 pts/2    00:00:00 sleep$ ./signal.sh 9 23277Sending SIGKILL signal$ sleep 1000Killed

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"        exitfi# Check the given file is exist #if [ ! -f $3 ]then        echo "Filename given \"$3\" doesn't exist"        exitficase "$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 textVim 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 textIt 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/bashfor 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"           ;;esacdone$ ./filetype.sha.c : C source fileb.c : C source filec1.txt : Text filefileop.sh : Shell scriptobj.o : Object filetext : Not processedt.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/bashecho -n "Do you agree with this? [yes or no]: "read ynocase $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.shDo you agree with this? [yes or no]: YESAgreed

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/bashcase "$1" in'start')echo "Starting application"/usr/bin/startpc;;'stop')echo "Stopping application"/usr/bin/stoppc;;'restart')echo "Usage: $0 [start|stop]";;esac$ ./startpcapp startStarting application/usr/bin/startpc started
原创粉丝点击