Detailed Anatomy of bash script programming

Source: Internet
Author: User

Detailed Anatomy of bash script programming


background: bash scripting is a crucial part of Linux learning, and it may be easy to complete a script, but it's not easy to make your own script write. Bash is almost always available for all Linux distributions, so let's take a bash script as an example to discuss how bash scripting is written. For some of the more important points in bash scripting, I'll give you a case demonstration.

I. Script programming in the preceding words:

As we all know, bash scripting is simply a stack of commands. But this stacking is not a messy accumulation, but in accordance with a certain requirements and format of the link. This shows that in learning programming at the same time, must have a large number of command base. This is like we used to write a composition, must have a lot of rhetoric basis to write the article full. Scripting is really the way it is, and it takes a lot of our own memory. In addition to develop the habit of more optimistic programming scripts, good places can be remembered. Over time, your own programming material will be more up.

Two. Basic knowledge and process outline of bash scripts:

First, the text of the script is named for the sake of distinction, and we all use. sh as the suffix. The first line of the script is to indicate the interpreter entry such as bash:#! /bin/bash. Be careful except #!. All lines starting with the # number are comment lines, except for the/bin/bash line. The text of the comment line is not used as a script execution procedure. The script should pay attention to the level of the script content when writing, and implement indentation between the levels. This allows the script to be adjusted at a glance. This is also a very important quality. In addition, the script often involves some expressions about the calculation, I am here to provide four methods, and then in the specific exercises to reflect the specific how to use:

1.$[expression] $ symbol in parentheses in the form of an arithmetic expression.

2.$ ((expresion)) $ character plus two parentheses plus the form of an arithmetic expression.

3.let var_name=expression let a variable be equal to the form of an expression.

4.$ (expr argu1 argu2 argu3) $ character parenthesis format

There are many ways to call a script after it has been written, such as we call a script called files.sh. We can add a execute permission to files.sh in the corresponding directory of the script: chmod +x files.sh, and then call it in this way directly./files.sh. Alternatively, we can also go directly to the command line: Bash-n stusum.sh first to see if there is a syntax error, then bash files.sh is called. For example:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/54/52/wKiom1R-_r3BC-N9AADy6e-tWDM848.jpg "title=" Bash2.png "alt=" Wkiom1r-_r3bc-n9aady6e-twdm848.jpg "/>

Three.bash script Programming flow control statements:

With this understanding of the basic process of scripting calls, it is possible to understand some specific syntax. Bash's scripting Process Control statements are broadly divided into: sequential execution, loop execution, select execution;. Variables are: Local variables, environment variables, special variables, positional parameter variables, local variables.

sequential execution of Process Control statements : sequential execution, as the name implies, completes the script-by-statement in the same way as before. For example:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/54/52/wKioL1R_CO2AX7RJAADNddlXnf8168.jpg "title=" he.png "alt=" wkiol1r_co2ax7rjaadnddlxnf8168.jpg "/>

Process Control Statement-Conditional execution: conditional execution is to meet a condition to go to the next step, not satisfied to skip the steps do not execute. The condition judgment is mainly the if type and the case type. First look at the IF type:

if format:if CONDITION; Then CMD ...; Fi This is a single branch if statement, that is, the condition satisfies the execution if the statement in the IF, otherwise skipped. Let's take a look at the following example:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/54/54/wKioL1R_VgLRAf9NAAClH8ADqBk258.jpg "title=" Zhangqingsong making 1.png "alt=" Wkiol1r_vglraf9naaclh8adqbk258.jpg "/>

analyze: For loop {1..9}. We use a single-branch statement to determine the condition,-le is an integer test condition, which means less than or equal. We have here a sum of less than equals 5 is naturally 15. Conditions for conditional execution statements can be divided into three categories:(1) integer test; (2) string test; (3) file test

1. Integer test:

Integer test: A, B

A-eq B: Equals

A-ne B: Not equal to

A-ge B: Greater than or equal to

A-GT B: Greater Than

A-le B: Less than or equal to

A-le B: Not equal to

For example, to indicate conditions A < B, you can write if [$A-lt $B];then
2. Character Test conditions:

Character string test: A, B

A > B

A < B

A >= B

A <= B

A = = B or a = B: equivalent comparison

A! = B: Not equal to

-Z A: Determine whether a is empty, empty is true, not empty is false;

-N A: Determine whether a is not empty, the value is not empty, the empty is false;

For example: We determine if an unknown character is know, and can be represented as if ["$A" = = "Keow"];then

Note: The character is judged to be the = number and the character to keep a space between to avoid error.

The above is a single-branch if statement when we want to indicate if not a, the case of B is. A single branch statement is not a good implementation at this point, so we have two branches and a multi-branch if statement. if condition-true; then CMD1; else CMD2; fi. If the multi-branch format is:

if TRUE; Then

Branch 1

Elif Condition2-true; Then

Branch 2

Elif Condition3-true; Then

Branch 3

...

Else

Branch N

Fi

Note: Here else can also not, in order to keep the uniform suggestion of the format reserved. Here is an example to familiarize yourself with this single-branch and multi-branch usage. For example: we want to implement the following function, to pass a user name to the script, if the user exists to determine whether its ID is less than 500, if less than 500 output, the user is the system user. If the ID is greater than 500, the output user is a normal user. If the given user name does not exist, we give the user added. For this topic we can first use their own language analysis, the framework first clear and then start.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/54/55/wKiom1R_NGqTk1_oAAEax5Mnuk4946.jpg "title=" Multi-if.png "alt=" Wkiom1r_ngqtk1_oaaeax5mnuk4946.jpg "/>

Note: The script pass parameter is used here, which is related to the special variable. Then find out what special variables are in the script for the ship. $* represents a list of passed parameters, such as three arguments outside A,b,c so $* represents a collection of three parameters for {a B c}. He can be used directly as a list in a loop, usually to define a list of passed arguments that we don't know. $# represents the number of arguments passed, such as passing 10 parameters to a script, $ #就为10. $ ... $n used to represent the number of arguments passed. For example, the first parameter that is passed is represented.

In fact, for this multi-branch if statement, there can be another concise way of case statements. Syntax structure for case: He says if a variable reference belongs to that pattern, it executes that branch accordingly.

Case variable reference in

PATTERN1)

Branch 1

    ;;

PATTERN2)

Branch 2

    ;;

...

*)

Branch N

    ;;

Esac

Below we will use case to implement the following functions. For example, we use the Tar tool to back up the/etc directory to the/backup directory with the name/backup/etc-date time. Tar. {XZ|BZ2|GZ};

(1) Display the following menu

#######################################

# XZ) xz Compress tool #

#gzip) gzip Compress tool #

#bzip2) bzip2 Compress tool #

#*) Wrong choice and quit #

#######################################

(2) According to the tool selected by the user, perform the corresponding action; If the user does not type any data, the default is XZ;


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/54/56/wKiom1R_WROy66SeAAJwJvdYDIc648.jpg "title=" bash " alt= "Wkiom1r_wroy66seaajwjvdydic648.jpg"/>



Note: [-Z $command] && command= "XZ" is actually another logical judgment to add a logical operator to the condition, while-Z indicates whether the file is empty. What it means: If the command is empty, execute command= "XZ" Besides this there are [-Z $command] | | Command= "XZ" it indicates that if command null is true, command= "XZ" is not executed. How does it look like a double branch if statement. In fact, this usage in the script instead of if is very common. In addition to this representation, it can be expressed as:

or,-o: [-Z ' $hostname "-o" $hostname "= = ' localhost ')

With,-a: [$uid-gt 0-a $uid-lt 500]

Non: [! EXPRESSION]

In addition to the various usages of the above conditions, in terms of judgment, sometimes we will use the document to judge. File judgment is such as determining whether a file exists, determining whether a file is a directory, determining whether a file has write permissions, and so on.

-e $file: exists or is true;

-a $file: ibid; discard;

-F $file: Whether the file exists and is a normal file;

-D $file: Exists and is a directory;

-H $file: exists and is a symbolic link file;

-L $file: Ibid.

-B $file: exists and is a block device file;

-C $file: Whether it exists and is a character device file;

-S $file: exists and is a socket file:

-P $file: exists and is a pipe file;


-R $file: Whether the current user has read access to this file;

-W $file: Whether the current user has write access to this file

-X $file: Whether the current user has Execute permission on this file;


-U $file: Whether the file has suid permissions;

-G $file: Whether the file has Sgid permissions;

-K $file: Whether the file has sticky permissions;


-O $file: Whether the current user is the owner of the file;

-G $file: Whether the current user belongs to the genus Group of the file;


-N $file: Whether the file has been modified since the last time it was read;


$f 1-nt $f 2: Is the document F1 newer than the F2 file;

$f 1-ot $f 2: File F1 is older than file F2;

$f 1-ef $f 2:f1 and F2 are hard links to the same file



Loop Execution of one of the process Control statements: loop Execution There is a for type, while type, until type; each has its own syntax, but there is a great similarity. Let's take a look at the for-loop:

For-loop format: for VAR in LIST;  Do STATEMENT1 ...; Done var is a variable that represents every one in the list. Lists are a list of numbers that determine the number of cycles. Do ... the done table is used to represent the start and end of the loop body. The part between do and do represents the loop body, which is the part that is executed each time the loop occurs. Let's take a simple for loop statement to look at the specific usage example: We add 10 users to the system: student1...student10.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/54/52/wKioL1R_DVTBfeQpAACCM3lh52o180.jpg "title=" Loop 2.png "alt=" wkiol1r_dvtbfeqpaaccm3lh52o180.jpg "/> Analysis: I variable represents 1. 10 of each number, List here is the curly brace {first. Last} indicates. The middle of two points must not be discarded. Do means that the condition begins to enter the loop, and done is the end position of the loop body. Well, let's take a look here. Several forms of the list of loops are generated:

1.{first. Last} curly braces for this expression.

2.seq first step last. Here seq is the command used here to command references such as: ' SEQ 1 2 100 ' which represents the odd part from 1 to 100.

3.globbing Wildcard Method For example: For I in/etc/* all sub-files in/etc directory

4. How the variable is referenced: $*, $#, etc.

5. List directly-this is one of the simplest and most brutal ways, but is limited to very few parameters.

Note: The For loop will automatically generate a list if omitted, but this practice is not advocated.

For loop nesting: Sometimes we need to use double or multiple loops in order to make the problem easier to implement in the loop. In this way, the nesting of loops is bound to be used. Nesting is actually the way that the outer loop loops one cycle at a time. For example, let's implement a 9*9 multiplication table to see the effect.

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/54/53/wKiom1R_FHjxZYFjAACX_6BxaTI016.jpg "title=" 99.png "alt=" wkiom1r_fhjxzyfjaacx_6bxati016.jpg "/> Analysis: Outer loop i{1..9}. According to our idea, the outer loop changes one time, and the inner cycle cycle is a cycle. When I is a cycle within 1 o'clock cycles. Loop {1: $i} at this time I is 1, which is actually 1x1. When i=2, the inner loop is still a period {1: $i}. This is the 1x1 1x2 followed by analogy. Then you just have to change the line every time you i=j, and Echo in the loop is the way to do it. \ t means to exit a tab and escape with-E. Also note that, I, j are variables, in order to ensure that the output of the character will not error, are enclosed in curly braces.



While loop format: While True;d o ... done this loop indicates that the loop starts when the condition is true. But the straight note is that when the conditional judgment is true in the while loop statement structure, it goes into the loop. And the structure does not give the loop out of the condition, so in the write loop, we must give the loop out of the condition. How to do this: for example, we want to monitor the current login system of a person named CentOS, every 5 seconds to refresh. If logged in, the CentOS is logged on. If not logged in, show no login.

#!/bin/bash

#

While true; Do

W.H.O. | grep "CentOS" &>/dev/null

If [$?-eq 0];then

Break

Fi

Sleep 5

echo "No login"

Done

echo "CentOS is logged."

~650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/54/56/wKiom1R_UUjh0JwlAADE-CID6AQ166.jpg "title=" Denglu.png "alt=" Wkiom1r_uujh0jwlaade-cid6aq166.jpg "/> In addition to this while can also be used to traverse the text of each row format as follows: while read line; Do loop body; done </path/from/somefile. Reads the text that is redirected to after done by the row. For example: Let's give a text file a random number of rows for the while statistic.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/54/56/wKiom1R_VKyBFpinAAB2PbnaJHY058.jpg "title=" Zhangqingsong production. png "alt=" wkiom1r_vkybfpinaab2pbnajhy058.jpg "/> until as a circular statement usage and while only the condition is judged to be the opposite, the rest of the usage is the same. That is, the loop is implemented when the until condition is false. Simple to use, friends can try it on their own, not here for example. The following article will be the array usage of Bash's functions.





























This article is from the "I and Linux years" blog, please be sure to keep this source http://guanqianjian.blog.51cto.com/9652236/1586148

Detailed Anatomy of bash script programming

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.