Shell Script Advanced

Source: Internet
Author: User

1. Process Control

Shell script is a procedural programming language, the process of programming language is divided into three types of execution, namely sequential execution, select execution, loop execution, these three execution methods to build all the contents of our shell script, we will introduce the three ways of execution.
1. Sequential execution
All commands in a shell script are executed sequentially, even if selection and looping are executed sequentially, so do not introduce them in particular.
2. Select Execute
Selection execution is when certain conditions are met, the statements in the selection are executed, and the selection is performed mainly in two ways, namely if selection execution and case selection execution.
If Select execute:
If the multi-layer if support nesting, can implement multi-layer selection execution, such as a simple if statement:

#!/bin/bashif [ $1 -ge 0 ];then                if [ $1 lt 9 ];then                                echo 这是一个大于等于0并且小于9的数                fifi

The results of the implementation are as follows:

As above, if is the start of the If selection, followed by the selection criteria, then the fixed syntax, followed by the statement to be executed when the selection condition is true, and fi is the flag to select the end.
Of course there are a number of options, and we can use elif and else to make other choices, such as a simple multiple choice:

#!/bin/bashif[ $1 -eq 0 ];then                echo 等于0elif[ $1 -eq 1 ];then                echo 等于1else                echo 非零且非1fi

We execute this script and execute the result as follows:

If select executes, only one selection branch can be matched at a time, and if no matching branch is executed, exit the selection directly.
Case Selection Execution:
Case is another choice structure, he is more than the if selection structure for multiple parallel selection branches, and case selection is a single match. Let's look at a simple case selection:

#!/bin/bashcase $1 in                 1)echo 输入的是1;;                2)echo 输入的是2;;                3)echo 输入的是3;;                4)echo 输入的是4;;esac

The results of the implementation are as follows:

Case selection is very convenient in this side-by-side scenario, where case represents the start of the selection structure and then the judging condition, ESAC is the flag that selects the end of the structure.
3. Cyclic structure
The loop structure is that when some conditions are met, some statements are executed in a loop until the loop is closed until a particular condition is met, and the loop structure consists of the following types:
For loop
The For loop is a loop when the loop condition is true, and ends the loop when the condition is false, such as a simple for loop:

#!/bin/bashfor i in `seq 1 3`;do                echo $i                echo 第$i次循环done

The results of the implementation are as follows:

For the For Loop, the for represents the start of the loop, followed by the loop condition, then the middle is the loop body, starting with do and done.
Another for loop is to enclose the loop condition in (()), with three conditions in the middle, separated by;

for ((i=0;i<10;i++));do                echo $i                echo 本次是第$i次循环done

The results of the implementation are as follows:

No matter which loops are convenient for looping, you can see that the appropriate for loop is selected
While loop
While loop is a loop structure that loops when the condition is true, we can see a simple while loop:

#!/bin/bashi=0while [ $i -lt 5 ];do                echo $i                echo 这是第$i次循环                let i++done

The results of the implementation are as follows:

In the while loop, the while is the start of the loop flag, followed by the judgment condition, if true, then start the loop, if False, then end the loop, do and done is the loop body.
Until cycle
Until loop and while loop instead, he enters the loop when the condition is false and ends the loop when the condition is true, let's take a look at the following example:

#!/bin/bashi=0until [ $i -eq 5 ];do                echo $i                echo 这是第$i次循环                let i++done

The results of the implementation are as follows:

In the until loop, the until is the start of the loop, followed by the loop condition, if the condition is false, then into the loop, if the condition is true, then the loop is closed, and between do and done is the loop body.
Select loop
Select is able to list the looping content, he needs an input value, and is saved in reply, for example

#!/bin/bashPS3=‘输入季节:‘select jijie in "春"     "夏"   " 秋"    "冬"    "退出";do        case $REPLY in                1)echo 春;;                2)echo 夏;;                3)echo 秋;;                4)echo 冬;;                5) exit ;;        esacdone

The results of the implementation are as follows:

Select represents the start of the loop, followed by the loop condition, and he will continue to loop until there is an exit.

2. Circular control commands

Break command
The break command can directly end the current loop structure, which is the exit loop, for example

#!/bin/bashfor i in `seq 1 3`;do                echo $i                echo 第$i次循环                                if [ $i -eq 2 ];then                                                break                                fidone

The results of the implementation are as follows:

You can see that when I equals 2 o'clock, the IF condition is met, then break is executed, the current loop ends directly, and no content after the break is executed, directly exiting the loop.
Break n You are a number that can end a loop of a specified number of layers.
Continue command
The continue command can end the current cycle and go directly to the next loop, after which the contents of the continue are not executed, for example:

#!/bin/bashfor i in `seq 1 3`;do                echo $i                                if [ $i -eq 2 ];then                                                continue                                fi                echo 第$i次循环done

The results of the implementation are as follows:

You can see that at I equals 2 o'clock, after executing to the Echo $i meet if condition, execute continue, direct end I equals 2 this cycle, do not perform echo $i cycle this sentence, directly proceed I equals 3 this layer loop.
Continue n N is a number that can be skipped over several layers of the current iteration.
Shift command
The shift command moves the argument list n times to the left, and N is the number, for example:

#!/bin/bashfor ((i=0;i<5;i++));do        echo $*        shiftdone

The results of the implementation are as follows:

Visible, each loop executes the shift command, which is the first parameter for all parameters of the output.
Shift n N is a number that causes the argument list to shift to the left N times, which is the first n arguments that start less each time.

3. Functions

A function is a collection of code, and when we define a function, we can call the function later, and it can be called repeatedly, not a single process, not run independently, but a part of the shell script, the life cycle of the function is the beginning of the call, and the end of the return.
Create a function
There are three ways to create a function:

1function f_name {...函数体...} 2function f_name () {...函数体...} 3f_name (){...函数体...}

Delete a function
The way to delete a function is unset plus the function name, for example:

unset  function_name

function parameters
Pass parameters to the function: When the function is called, the given argument list is separated by a blank space after the function name, for example:

function_name 参数1 参数2 ······

So we can use $1,$2, in the function. $n to reference these parameters
function file
We can create our own function files, which can be either your own or a required function.
Function call
We can call what we write or the system's built-in functions to meet our needs.
The function file is called in the following way:

.+空格+函数文件名或者source+空格+函数文件名

The functions in the call script are played in the following way

function_name

Direct file name, if there are parameters, you can add parameters later.
Environment variables, local variables and local variables
The environment variables defined in the function are valid in the function as well as the current shell, the current Shell's child shell, and the local variable is valid only in the function, the local variable is valid only in the current shell and function, and is not valid elsewhere.
Here's how to set up local variables:

local can=3

function recursion
function recursion refers to the function itself can call itself directly or indirectly, when the deepest layer has a return value after the return value is gradually returned.
function return value
There are two cases of return values:
1
The return value of the function's execution result:
(1) Output using commands such as Echo
(2) output of the call command in the function body
2
Exit status code for the function:
(1) The default depends on the exit status code of the last command executed in the function
(2) Custom exit status code, in the form of:
Return returned from the function, with the last state command to determine the return value
return 0 returns without error.
Return 1-255 has error returned

4. Arrays

An array is a contiguous memory space that stores multiple elements, which is equivalent to a collection of multiple variables, and we can apply the values in the array in the following way:

${ARRAY_NAME[INDEX]}

Array_Name is the array name, index is the array subscript
Create an array
There are four ways to create an array

declare -a ARRAY_NAMEdeclare -A ARRAY_NAME

-A is to create an associative array
Assigning a value to an array
There are 4 main ways to assign values to an array, as follows:

(1) 一次只赋值一个元素;ARRAY_NAME[INDEX]=VALUEweekdays[0]="Sunday"weekdays[1]="Thursday"(2) 一次赋值全部元素:ARRAY_NAME=("a" "b" "c" ...)(3) 只赋值特定元素:ARRAY_NAME=([0]="VAL1" [3]="VAL2" ...)(4) 交互式数组值对赋值read -a ARRAY

Referencing all elements of an array

${ARRAY_NAME[*]}${ARRAY_NAME[@]}
数组的长度(数组中元素的个数):${#ARRAY_NAME[*]}${#ARRAY_NAME[@]}

Append an element to an array

ARRAY[${#ARRAY[*]}]=value

Shell Script Advanced

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.