Use of case in shell learn notes _linux shell

Source: Internet
Author: User
Tags case statement

Case statements in the shell:

You can match the contents of a variable with multiple templates, and then decide which part of the code should be executed based on a successful matching template.

Use format:
Case matching Parent board in
Template 1 [| template 2] ...) Statement group;;
Template 3 [| template 4] ...) Statement group;;
Esac
The case statement matches the order from top to down. Therefore, the principle of the case statement is written from the top down, the template from special to ordinary. In C, there is a default template in the case statement, and in Shell programming, the template may be written in * to accomplish the same function.

Example 1:

Copy Code code as follows:

#!/bin/sh
echo "Please input \" yes\ "or \" No\ ""
Read Var
Case "$var" in
[YY] [EE] [SS]) echo "Your input is YES";;
[NN] [OO]) echo "Your input is no";;
* echo "Input error!";;
Esac
Exit 0

Example 2:

Copy Code code as follows:

#!/bin/bash
Fruit=$1 #注意没有空格
If [z ' $] #中括号跟-Z to have spaces
Then
echo "does not enter fruit in the first argument"
Else
Case "$FRUIT" in
apple| Apple) echo "The FRUIT is Apple";;
banana| BANANA) echo "The Frult is BANANA";;
#可以使用 *) to indicate the default option, and note that the end is to end with a two semicolon
*) echo "Did you enter the fruit I asked for?" ";;
Esac
Fi

#---A value that is both an external argument, such as: When the script is run:./test.sh Apple
#---here, Apple is a $

An additional example is attached:

Copy Code code as follows:

#!/bin/bash
hosts= "nss.sh cs.sh ss.sh ds_handler2 Tomcat Blog httpd"
For MyHost in $HOSTS
Todo
Count= (' PS aux |grep-v grep |grep $myHost |wc-l ')
Echo $myHost
Echo $count
Done

Related Article

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.