[Happy BASH] BASH的case语句学习

The case statement

Syntax

The syntax is as follows:

          case  $variable-name  in
                pattern1)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                pattern2)
     		    command1
                    ...
                    ....
                    commandN
                    ;;            
                patternN)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                *)              
          esac 

OR

          case  $variable-name  in
                pattern1|pattern2|pattern3)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                pattern4|pattern5|pattern6)
     		    command1
                    ...
                    ....
                    commandN
                    ;;            
                pattern7|pattern8|patternN)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                *)              
          esac 
  • The case statement allows you to easily check pattern (conditions) and then process a command-line if that condition evaluates to true.
  • In other words the $variable-name is compared against the patterns until a match is found.
  • *) acts as default and it is executed if no match is found.
  • The pattern can include wildcards.
  • You must include ;; at the end of each commandN. The shell executes all the statements up to the two semicolons that are next to each other.
  • The esac is always required to indicate end of case statement.

Example

Create a shell script called rental.sh:

#!/bin/bash
 
# if no command line arg given
# set rental to Unknown
if [ -z $1 ]
then
  rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as a rental
  rental=$1
fi
 
# use case statement to make decision for rental
case $rental in
   "car") echo "For $rental rental is Rs.20 per k/m.";;
   "van") echo "For $rental rental is Rs.10 per k/m.";;
   "jeep") echo "For $rental rental is Rs.5 per k/m.";;
   "bicycle") echo "For $rental rental 20 paisa per k/m.";;
   "enfield") echo "For $rental rental Rs.3  per k/m.";;
   "thunderbird") echo "For $rental rental Rs.5 per k/m.";;
   *) echo "Sorry, I can not get a $rental rental  for you!";;
esac

Save and close the file. Run it as follows:

chmod +x rental.sh
./rental.sh 
./rental.sh jeep
./rental.sh enfield
./rental.sh bike

Sample outputs:

Sorry, I can not get a *** Unknown vehicle *** rental  for you!
For jeep rental is Rs.5 per k/m.
For enfield rental Rs.3  per k/m.
Sorry, I can not get a bike rental  for you!

The case statement first checks $rental against each option for a match. If it matches "car", the echo command will display rental for car. If it matches "van", the echo command will display rental for van and so on. If it matches nothing i.e. * (default option), an appropriate warning message is printed.

Using Multiple Patterns

#!/bin/bash
NOW=$(date +"%a")
case $NOW in
	Mon)	
		echo "Full backup";;
	Tue|Wed|Thu|Fri)
		echo "Partial backup";;
	Sat|Sun)	
		echo "No backup";;
	*) ;;
esac

The following shell script demonstrate the concept of command line parameters processing using the case statement (casecmdargs.sh):

#!/bin/bash
OPT=$1   # option
FILE=$2  # filename
 
# test -e and -E command line args matching
case $OPT in
  -e|-E) 
  	echo "Editing $2 file..." 
        # make sure filename is passed else an error displayed   
  	[ -z $FILE ] && { echo "File name missing"; exit 1; } || vi $FILE	
  	;;
  -c|-C) 
  	echo "Displaying $2 file..." 
  	[ -z $FILE ] && { echo "File name missing"; exit 1; } || cat $FILE	
  	;;
  -d|-D) 
  	echo "Today is $(date)" 
  	;;
   *) 
    echo "Bad argument!" 
    echo "Usage: $0 -ecd filename"
    echo "	-e file : Edit file."
    echo "	-c file : Display file."
    echo "	-d      : Display current date and time."	
    ;;
esac

Run it as follows:

chmod +x casecmdargs.sh
./casecmdargs.sh
./casecmdargs.sh -e /tmp/file
./casecmdargs.sh -E /tmp/file
./casecmdargs.sh -e 
./casecmdargs.sh -D

Creating a backup script

Create a backup script called allinonebackup.sh:

#!/bin/bash
# A shell script to backup mysql, webserver and files to tape
opt=$1
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
        	    echo "Backup shell script utility"
                echo "Usage: $0 {sql|sync|tar}"
                echo "	sql  : Run mySQL backup utility."
                echo "	sync : Run web server backup utility."	
                echo "	tar  : Run tape backup utility."	;;
esac

Save and close the file. Run it as follows:

chmod +x allinonebackup.sh
# run sql backup
./allinonebackup.sh sql
# Dump file system using tape device
./allinonebackup.sh tar
# however, the following will fail as patterns are case sensitive
# you must use command line argument tar and not TAR, Tar, TaR etc. 
./allinonebackup.sh TAR
backup shell script utility
Usage: ./allinonebackup.sh {sql|sync|tar}
	sql : run mysql backup utility
	sync: run web serve backup utility
	tar : run tape backup utility


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值