Case Statements

team bbl


Case statements allow you to test a string using a series of patterns, executing only the commands for the matching pattern. The general format of the case statement is:

 case string in     pattern_1)         commands         ;;     pattern_2)         commands         ;;    pattern_3)         commands        ;; ... esac 

The patterns you can use are:

  • * Matches any string of characters.

  • ? Matches any single character.

  • […] Matches any character or a range of characters in the brackets. A range is specified with a hyphen (e.g. A-Z or 1-4).

  • | Matches the pattern on either side of the | (e.g., John|Sam).

An example case statement is:

 #!/bin/bash name=John case $name in     john|John)         echo Welcome $name         ;;     sam|Sam)         echo Hello $name         ;;     *)         echo You're not invited        ;; esac 

The * is used for the last case, to handle all the conditions not listed specifically in previous sections of the case statement. Any string that doesn't contain John or Sam's name matches the last case.

    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net