Bourne/bash shell scripts: case statement

Home -> Programming -> Shell script -> Bourne shells

92280 views

From the computer of: Rex (39 recipes)
Created: Oct 22, 2003     Updated: Aug 30, 2004


4 comments:
View all comments

Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

The case statement is an elegant replacement for if/then/else if/else statements when making numerous comparisons. This recipe describes the case statement syntax for the Bourne shells (sh, ksh, bash, zsh, etc.).

case "$var" in
    value1)
         commands;
         ;;
    value2)
         commands;
         ;;
    *)
         commands;
         ;;
esac


The case statement compares the value of the variable ($var in this case) to one or more values (value1, value2, ...). Once a match is found, the associated commands are executed and the case statement is terminated. The optional last comparison *) is a default case and will match anything.

For example, branching on a command line parameter to the script, such as 'start' or 'stop' with a runtime control script. The following example uses the first command line parameter ($1):

case "$1" in
     'start')
         /usr/app/startup-script
         ;;
     'stop')
         /usr/app/shutdown-script
         ;;
     'restart')
         echo "Usage: $0 [start|stop]"
         ;;
esac

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.




4 Recipe comments: View comments

Bourne/bash shell scripts: case statement by hpx
error in case by Anonymous
Re: Bourne/bash shell scripts: case statement by Anonymous
Re: error in case by sttyecho



Related recipes:

  Bourne/bash shell scripts: if statement syntax
  Bourne/bash shell script for loop syntax
  Hide password entry in Bourne/bash shell script
  Bourne/bash shell script: while loop syntax
  Bourne/bash shell script functions
  Determine if file exists in a Bourne/bash shell script
  Determine if a file is writable by a Bourne script user
  Bourne/bash shell scripts: string comparison
  bash shell script iterate through array values
  bash shell script declaring/creating arrays

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.