Play Bash script: Select the case of the structure

Source: Internet
Author: User
Tags case statement character classes control characters posix printable characters

Total 5th article

Before we talked about if. This time we'll talk about another alternative structure--case. Case and if

If the condition is used for selection, not a lot of circumstances, if the choice of conditions too much, a series of If,elif, is also drunk. Yes, the case in bash is the same as the switch's position in C. But the usage can be very different. code block

Any language has the concept of a block of code, the curly braces in C language {},python in the colon and indentation. The code block style in bash is not very uniform. But in the choice of structure is the same- irony . The IF structure uses if...fi to identify the scope of a block of code, and case is used to represent a block scope with Case...esac .
Basic Structure

See Example echo.sh:

#!/bin/bash
str= "is good"
read-p "What color do you like:" Color case
$color in
    red) echo-e "\e[1;31m$color $str \e[0m ";;
    Green) echo-e "\e[1;32m$color $str \e[0m";
    Yellow) echo-e "\e[1;33m$color $str \e[0m";;
    Blue) echo-e "\e[1;34m$color $str \e[0m";;
    * ECHO-E "\e[1;30m What color is this?" \e[0m ";;
Esac
This code, is based on your input to display different colors of text. The expression of the Echo statement is not discussed here, and each sentence has a different text color. Focus on looking at this structure.

Compare the value of the variable color, followed by the value in the right bracket below, and execute the following statement if the same.

To run
two semicolon;;

Note that each condition has a two semicolon at the end. This is well understood, like the C-language switch where every case often has a break. Because each condition satisfies, the statement that needs to be executed may be more than one sentence. In bash, multiple statements are separated by a semicolon at a single line. Such a two semicolon means the end of the statement, plus an empty statement, which means that the statement to be executed is complete.

Unlike the C-language switch, each condition (case statement) in C is not necessarily followed by a break, and if there is no break, the statement of the following condition continues. What if you want to share a set of statements in C with multiple conditions? Please continue reading. semicolon Twist number;&

The so-called twist number, is and symbol--&, I think the name is more concise. Read a section of C code:

#include <stdio.h>
int main () {
    char ans;
    printf ("Do you like to program:");
    scanf ("%c", &ans);
    Switch (ANS) {case
        ' y ': case
        ' y ':p rintf ("I am also");
        Case ' n ': Case
        ' n ':p rintf ("Sorry, nothing to talk to You");
That is, in C, if the case is not followed by a break, after the matching statement is executed, the execution is followed, regardless of the following conditional matching mismatch until a break is encountered. This syntax is very flexible, so how do you implement bash? Do you add a semicolon to the end? Wrong or wrong. The answer is a semicolon plus a twist.

#!/bin/bash
read-p "Do you like Programming: (y/n):" Ans case
$ans in
    y);&
    y) echo "I am also";;
    N);&
    N) echo "Sorry, nothing to talk to you";
Esac

Semicolon, semicolon, and twist number;; &

In addition to;& concluding sentence, there is another one is;; & To end the usage of the statement. But the meaning is different;; The use of & is to make conditions more accurate .

#!/bin/bash
read-p "Please enter an area code:" Num case
$num in
    *) echo-n "China";; &
    03*) echo-n "Hebei province";; &?
        ? echo "Hanhan";;?
        ? One) echo "Shijiazhuang";?
        ? echo "Cangzhou";;
    07*) echo-n "Jiangxi Province";; &?
        ? ) echo "Nanchang";??
        ) echo "Jiujiang";??
        ) echo "Ganzhou";
Esac

About wildcard characters * and. , as we'll talk about here. Here, you just need to know, conditional statements to;; At the end of the &, the program executes here without stopping, and will continue to test the following conditions if satisfied to continue execution until encountered;; or ESAC


Note that the use of these two types of torsion is Bash's own feature and is not supported for other shells. If you're considering portability, don't write that. Just use a regular two semicolon.

the pattern in the right parenthesis Basic Regular

Right parenthesis, similar to the case in switch in C language. The difference, however, is that inside the right parenthesis in bash, not only does it support the full string (only integer data is supported in the C language, including int and Char

, no strings are supported) and "pattern" matching is also supported. The concept of patterns, if you understand regular expressions, then it is easy to understand. However, the case statement is slightly different from the regular expression. Seemingly supportive is not complete. * is to match 0 or more of any characters ... is to match one character. Can be seen as a placeholder. [] represents a range. () an enumeration string. But you need to escape

#!/bin/bash
read-p "Please enter a number:" Num case
$num in
    2*) echo "Match 2*";; &
    2?) echo "Match 2?"; &
    [0-9]) echo "match [0-9]";;
Esac
Brackets represent ranges, and you can use [123] to match 1 or 2 or 3 instead of 123. can also use [0-9], [a-za-z] such writing, familiar with regular students, these are not a problem.

Notice what I have used above;; & that means that after a pattern is matched, it does not stop and continues to execute downward. Execution effect:

Enumeration String

General wording such as (123|456|789) matches 123,456,789 of these three numbers. However, because the right parenthesis in the case has a special meaning, it is escaped.

Then my writing is (123|456|789\), but there is a problem is that 789 can not be matched, 123 and 456 is OK, I am also unknown so (laugh, know people hope to inform).

So I changed a version, finally match completely--(123|456|789|\).

Now add a sentence to just the script-(123|456|789 \)) echo "Match (123|456|789|\)";; &

POSIX character Classes

Regular expressions in a generic programming language that support character classes such as \w,\d (Character Classes). On the unix-like system, the supported character classes are POSIX-style.

See table below

Class

Description

Extension

[: Alnum:]

alphabetic and numeric characters

[0-9a-za-z]

[: Alpha:]

(Letters) alphabetic characters (Letters)

[A-za-z]

[: ASCII:]

7-bit ASCII

[\x01-\x7f]

[: Blank:]

Horizontal whitespace characters (spaces, tabs)

[\ t]

[: Cntrl:]

Control characters

[\x01-\x1f]

[:d Igit:]

Digital

[0-9]

[: Graph:]

Characters printed in ink (not spaces, non-control characters)

[^\x01-\x20]

[: Lower:]

lowercase letters

[A-z]

[:p rint:]

printable characters (graphic classes with spaces and tabs)

[\t\x20-\xff]

[:p UNCT:]

Any punctuation, such as a period (.) and semicolons (;)

[-!" #$%& ' () *+,./:;<=>?@[\\\]^_ ' {|} ~]

[: Space:]

Blank (newline, carriage return, tab, space, Vertical tab)

[\n\r\t \x0b]

[: Upper:]

Capital

[A-z]

[: Xdigit:]

hexadecimal digits

[0-9a-fa-f]

This table is copied from the net friend, the original "POSIX style regular expression"

When you actually use them, you also need to set the brackets outside these character classes.

#!/bin/bash
read-p "Please enter any, you can include whitespace and other blank characters" ch
#echo $ch case
$ch in
    *[[:lower:]]*) echo lower;; &
    *[[:upper:]]*) echo Upper;; &
    *[[:d igit:]]*) echo digit;; &
    *[[:p unct:]]*) echo punct;; &
    *[[:ascii:]]*) echo ASCII;; &
    *[[:cntrl:]]*) echo cntrl;; &
    *[[:p rint:]]*) echo print; &
    *[[:space:]]*) echo space;; &
    *[[:xdigit:]]*) echo xdigit;; &
    *[[:graph:]]*) echo graph;; &
    *[[:blank:]]*) echo blank;; &
    *[[:alnum:]]*) echo alnum;; &
    *[[:alpha:]]*) echo Alpha;; &
Esac

This script, everyone to test it. Of course, some characters (such as control characters) seem to be difficult to enter. This is not good test [: Cntrl:] This character class, here I tell you, the ASCII code 27 corresponding control character is ESC. When you test the script, you can click the ESC key. or type the ^[ character, and the same.


For more articles in this series (Play bash script), please visit: http://blog.csdn.net/column/details/wanbash.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.