Shell Script Tutorial

Logic - CASE

The case Statement

Bash provides a case statement that lets you compare a string with several possible values and execute a block of code when it finds a match. Here's an example of the case command, with the syntax shown in boldface and the parts you would supply in normal type:

case $1 in -a) commands;; -f) commands;; *) commands;; esac

In this example, if the value of $1 was -a, the first block of commands would execute. If the value of $1 was -f, the second block of commands would execute. Otherwise, the third block of commands, following the asterisk clause, would execute. (Think of the asterisk as meaning "match anything.")

You can put as many commands as you need in place of commands in the sample, but be sure to end the block with a double semicolon. Only the first matching block of commands will execute in a case statement, and you must signal the end of the construct with the esac command.

Example for CASE

read ans case $ans in y) echo "yes" ;; n) echo "no" ;; *) echo "other" ;; esac



Server is hosted by Alanstudio
Linux Operating System

Recommend screen resolution 1024 x 768 / IE / FireFox
Alan Studio © 2007 by Alan Cheung Hin Lun. All rights reserved.