Shell functions and arrays

Source: Internet
Author: User
Tags array definition save file variable scope

1. What is a function

A named block of statements; a boundary with a beginning and an end;

Begin ... end

2, the statement block in the shell statement

(1), (statement 1; statement 2; ...)

(2), {statement 1; Statement 2; ...}

(3), if else elif while for

(4), a named block of statements, functions;

3. Definition of Shell function

Features of the function: (1), Function name (2), statement block (3), return value (4), parameter

The Shell function defines 2 basic formats:

(1)

Function name () {

$

Several statements

}

Return value type: Is an integer that is stored in the environment variable at the end of the function call;

Parameters: Parameters are passed by positional variables.

Defines a function that does not execute the statement in the function, but only after the calling function, which is invoked directly in the shell with the function name.

#!/bin/bashfunction Show () {echo "Hello"}show

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/86/EC/wKiom1fOvFqCPL3-AAAa-oIHcdA605.png-wh_500x0-wm_3 -wmp_4-s_2456835133.png "title=" Qq20160906205336.png "alt=" Wkiom1fovfqcpl3-aaaa-oihcda605.png-wh_50 "/>

(2)

Function name () {

Several statements

}

#!/bin/bashshow () {echo "Hello"}show

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/86/EB/wKioL1fOvMSDMzmgAAAbmVeHHRE950.png-wh_500x0-wm_3 -wmp_4-s_3193008921.png "title=" Qq20160906205515.png "alt=" Wkiol1fovmsdmzmgaaabmvehhre950.png-wh_50 "/>

4. Invocation of Shell functions

The Shell function call is the same as when the command was called, and after writing a function, the function is equivalent to an internal command of the shell.

Attention:

(1), the function must be defined after the call, because base is parsed and executed line by row;

(2), write the function best: Write all the function definition in the front, where no command execution, all the executed commands are written in the entire shell file in the second half.

(3), Shell in the execution of a command line, first in the shell process to manage the function table to query the function of the name , if any, then call the function, if not, then look for internal command, found to execute, if the internal command is not found, In the PATH environment variable to find the corresponding external command, find the execution, if not found, then the error command not found;

(4), when writing shell script definition functions, cannot be the same name as internal command or external command.

5. Variable Scope

The scope of a variable refers to the range in which the variable can function;

Any position in a shell script is given a variable, which is a user variable, and the user variable is globally valid throughout the shell process, in other words, the variables directly defined in the shell can be considered global variables, but need to be aware of the order of execution;

The global variables will cause the running characteristics of many running functions to change, and for this, the solution is as follows:

(1), using the features provided by bash, this feature is provided by bash internal command local, when defining variables in the function body, add the local command before the variable, you can make the variable function only in functions; not a user variable, but a local variable in bash. Bash's internal command local can only be used in the function definition body.

#!/bin/bashhello () {local username=madong echo $userName}echo "before Hello:" $userNameHelloecho "after Hello:" $userName

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/86/ED/wKiom1fO11yxBSxTAAA2RIpX5ys546.png-wh_500x0-wm_3 -wmp_4-s_3735695658.png "title=" Qq20160906224845.png "alt=" Wkiom1fo11yxbsxtaaa2ripx5ys546.png-wh_50 "/>

6. Shell Array

(1), Format: shell array definition requires the use of special Symbols: ()

Variable name = (string 1 string 2 string 3 ...)

Variable name = ([subscript index]= string 1, ...)

(2), searching for array elements according to subscript

${array variable name [subscript]}; subscript starting from 0;

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/86/EE/wKiom1fO4N7R2NIWAAAtv-uzDSQ748.png-wh_500x0-wm_3 -wmp_4-s_4028460070.png "title=" Qq20160906232920.png "alt=" Wkiom1fo4n7r2niwaaatv-uzdsq748.png-wh_50 "/>

(3), some operations on the array

I> get all elements of the array:${array variable name [*]}; ${array variable name [@]}

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M01/86/ED/wKioL1fO4g7A0SO0AABTljWDKCA624.png-wh_500x0-wm_3 -wmp_4-s_194677052.png "title=" Qq20160906233131.png "alt=" Wkiol1fo4g7a0so0aabtljwdkca624.png-wh_50 "/>

Ii> get array Length: ${#数组变量名称 [*]}; ${#数组变量名称 [@]}

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/86/EE/wKiom1fO4czCtSMGAABzDeqx_iE628.png-wh_500x0-wm_3 -wmp_4-s_1582536117.png "title=" Qq20160906233251.png "alt=" Wkiom1fo4czctsmgaabzdeqx_ie628.png-wh_50 "/>

Iii> Array Traversal: iterating through an array by subscript, but with limitations, this traversal is invalidated if the index of the array being traversed is non-contiguous.

Traverse the code:

#!/bin/bashindex=0erray= (ABC def GHI LMN OPQ rst) while test $index-lt ${#array [*]}do echo ${array[$index]} index= ' E xpr $index + 1 ' done

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/86/ED/wKioL1fO5MaBC3rcAAAXfpqXiqQ135.png-wh_500x0-wm_3 -wmp_4-s_1505433911.png "title=" Qq20160906234604.png "alt=" Wkiol1fo5mabc3rcaaaxfpqxiqq135.png-wh_50 "/>

Traverse directly through the For loop

#!/bin/basharray= (ABC def XYZ) for Var in ${array[*]}do Echo $vardone

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/86/EE/wKiom1fO5U2B8eCTAAAeoD0yIlg000.png-wh_500x0-wm_3 -wmp_4-s_3025266909.png "title=" Qq20160906234820.png "alt=" Wkiom1fo5u2b8ectaaaeod0yilg000.png-wh_50 "/>

The shell array is defined with (); Use {};

7, some more flexible use

(1), array interception: To find a continuous subset of subscript

${array variable name [@]: Start subscript} #从起始下标开始, intercept all the remaining elements to form a new array;

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M01/86/ED/wKioL1fO6HCQSal9AAAutTw3sSA432.png-wh_500x0-wm_3 -wmp_4-s_1445794806.png "title=" Qq20160907000138.png "alt=" Wkiol1fo6hcqsal9aaauttw3ssa432.png-wh_50 "/>

${array variable name [@]: Start subscript: Length} #从起始下标开始, intercept the length of elements to form a new array;

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/86/ED/wKioL1fO6Y2gqIZTAABIIpQV6L4963.png-wh_500x0-wm_3 -wmp_4-s_3185584952.png "title=" Qq20160907000455.png "alt=" Wkiol1fo6y2gqiztaabiipqv6l4963.png-wh_50 "/>

The @ symbol can also be changed to *

(2), modify the value of the array element and the number of elements

i> array Name [subscript]= string

If the value of the underlying is greater than the current number of elements in the array, the array subscript index range is expanded, and a new element is added to the group.

Number of array elements: number of non-empty string elements in an array

(3), to delete an array, format:

The array name [subscript]= "" #并没有真正的删除数组元素, but simply empties the value of the array element and the number of elements in the array does not change;

unset array name [subscript] #彻底删除了数组元素, the number of array elements will be reduced;

Note: None of the elements behind the deleted element will automatically move forward;

Inference: The subscript of the shell array element can be discontinuous, even when the array is defined, its subscript index is discontinuous,

8. Shell programming to realize student information management

Achieve the simplest input, and save file functions:

#!/bin/bashif ! [ -e ./stddata.txt ]then    echo  "Student name   Student age   Student sex   student Email " >> ./stdData.txt    echo "----------------- ------------------" >> ./stddata.txtfistdname=" "stdage=" "stdsex=" "stdmail=" "while test  1 -eq 1do    read -p  "Please input student name  :  " stdname    stdnamelength= ' expr length " $stdName "     if test  $stdNameLength  -lt 10 -a  $stdNameLength  -gt  0    then        break    else         echo  "Input erroe"     fi   done    while test 1 -eq 1do    read -p   "PLEASE INPut student age :  " stdAge    if test  $stdAge  -gt  10 -a  $stdAge  -lt 18    then         break    else        echo  "Input  erroe "    fidonewhile test 1 -eq 1do    read  -p  "Please input student sex (f: Female  m: male)  : "  stdSex     if test  $stdSex  = f -o  $stdSex  = m     then        break    else         echo  "Input erroe"     fidonewhile test 1  -eq 1do    read -p  "please input student mail : "  stdMail    stdmaillength= ' expr length  "$stdMail" '     if test $ stdmaillength -gt 10    then         break    else        echo  "Input ERROE"     fidoneecho  $stdName   $stdAge   $stdSex   $stdMail  >> ./ StdData.txt

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/86/F0/wKiom1fPS-WykZ96AABsxuE03X4184.png-wh_500x0-wm_3 -wmp_4-s_2649717396.png "title=" Qq20160907070321.png "alt=" Wkiom1fps-wykz96aabsxue03x4184.png-wh_50 "/>

Query the results in the file:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/86/EF/wKioL1fPTBCxJVR6AAAf7CqgYPU319.png-wh_500x0-wm_3 -wmp_4-s_343570357.png "title=" Qq20160907070633.png "alt=" Wkiol1fptbcxjvr6aaaf7cqgypu319.png-wh_50 "/>


This article is from the "11586096" blog, please be sure to keep this source http://11596096.blog.51cto.com/11586096/1847073

Shell functions and arrays

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.