The seven-function application of Linux shell

Source: Internet
Author: User
Tags naming convention

What is a function?

A function is a collection of commands, represented by a name, called a function name. The function name has the same naming convention as the variable.

Once the function is defined, execute the name as if it were a bash command called a call function. In fact, when bash invokes a function, it executes the command area in the function and executes

After that, Bash goes back to the next line of the calling function to continue execution.

The most important function of the functions is to allow the program to be modularized. If you need to execute a command area repeatedly in a script program, you should use a function to represent the area, on the one hand, to streamline the program, while the program code page is relatively easy to maintain.

First, the use of functions

1. Syntax for functions

Syntax 1:

Function name ()

{

Command Area

}

The function name and () can be directly connected or separated by a space.

Syntax 2:

Function name ()

{

Command Area

}

Keyword function can be omitted

Syntax 3:

Function name

{

Command Area

}

If you use the keyword function, you can omit the () name

Example:

#!/bin/bash

Getline () #定义函数getline to define the number of file rows

{

Local i=0 #i代表已计算的行数, first return to 0.

#local用来设定变量i是getline函数中专有的变量, does not affect the function called I in other places of script

While Read line

Do #使用while循环, argument value $file specifies that the file reads each row

Let ++i #每读一行 variable i value +1

Done < $file #使用转向输入, so read can read data by $file

echo "$file file has $i lines" #显示总行

}


File=$1 #由命令行第一个参数 to obtain the file name to count the number of rows.

Getline #调用getline函数

echo "Getline execution Complete" #getline执行完后, back here to continue with the next instruction.

#./script passwd

passwd file Total 36 lines

Getline execution Complete

Be sure to define the function before calling the function.

Unset-f function Cancellation function

2. End state of function

When executing a function, the return value of the last command in the function represents the end state of the function. Executes the function if it encounters a return command, it ends immediately, returning to the next command that invokes the function, at which time the function returns a value of 0.

#!/bin/bash

Getline ()

{

Local i=0

While Read line

Do

Let ++i

if ($i >); then #判断是否超过10行

echo "$file file greater than 10 lines, no longer continue"

Return #遇到return命令, return immediately to echo$?

#默认传回值为0, you can also specify a different return value, directly in the return space plus a number

Fi

Done < $file

echo "$file file $i line"

}


File=$1

Getline

echo $?

echo "Getline execution Complete"


Can be based on $? The value of (return to number N) executes the desired command, such as If[$?-eq 3];then

echo "Too many rows, discard read"

Else

Echo ' Getline execution complete '

Fi

The function and the scope of the variable.

1, function of the scope

function is only valid in a defined shell environment, and when bash executes a function, it does not open another child shell.

If you want to pass a function to the shell environment, you can use the built-in command to export-f the function name so that the function becomes part of the environment variable (the function type) that can be called by the child Shell's script.

2, the scope of the variable

If there is no particular set of properties for a variable, the variable that is customized in script is called a global variable (for this script). The scope of the action is valid throughout the script file.

#!/bin/bash

Getline ()

{

Local i=0 #这就定义了变量i只在函数getline中有效, variable i and other variables called I are completely different.

While Read line

Do

....

Three, Position parameters

1. Location parameters of command line

$ A indicates that the script name, $ (10), represents the first parameter, and the 2nd parameter is the 10th argument

$* represents all positional parameters and is viewed as a string. 1.sh A x y $* to "A x y"

[email protected] represents all whitespace-separated parameters, each position is serial. 1.ah a x y [email protected] is "a", "X", "Y"

$# the number of positional parameters, 1.ah A x y is $ #的值为3

#!/bin/bash

If [$#-ne 2];then must type 2 parameters, otherwise an error exits

echo "How to use:./$0 parameter 1 parameter 2"

Exit 1

Fi

2. Moving position parameters

Bash's built-in command shift can move forward the value of the positional parameter, with the following syntax:

Shift N

n is a positive integer that represents the number of moves forward. n can be omitted without writing the delegate to move once. The value of Shift n,$ (N+1) is placed in the

To execute the SHIFT command (not specified), the value of $ $ is put into the value of $1,$3 and put into $ $2,$4, and if you keep the shift (number of times >=n), all the positional parameters are emptied

Shift clears 1 (starting from $), shift 21 clears 2

#!/bin/bashecho "\[email protected" initial value is [email protected] "while shiftdo[-n" $ "&& echo" Shift 1 times, \[email Prote CTED] Changes: [email protected] "Done execution results: [[email protected] tmp]# bash 1.sh a b c d e [email protected] Initial value is a B c D Eshift 1 times, [Email protected] Changes: b c D Eshift 1 times, [email protected] Changes: C D eshift 1 times, [email protected] Changes: D Eshift 1 times, [email protected] Changes in: E

3. Specify the value of the positional parameter

The value of the specified positional parameter is called reset (reset), set with the bash command

#!/bin/bashdeclare-i i=0set [email protected] do (i++) echo "first $i position parameter $ $i = $p" #$$ current BAS H Shell process number Done[[email protected] tmp]# bash 2.sh 1th position parameter 3547i = 10 2nd position parameter 3547i = 20 3rd position parameter 3547i = 30 4 Position parameter 3547i = 40 5th position parameter 3547i = 50

Once the position parameter is reset with set, its original value disappears and is replaced with the new value. (no matter how many parameters are entered, the set setting is several)

If you want to reset all parameters at once so that their values are empty, you can execute set--

4. Take the command line options and parameters

When designing a script, it is often necessary to obtain the user-supplied options and parameters from the command line, and depending on the options, the script has different processing and execution results. Options can be used in a way that

is a single option, you can also add a ready-to-work parameter to the option, and the order of options appears without strict requirements.

As in the following example:

./script-u Jacken-a-H

Or use the following form

./script-a-U jacken-h

If you want to get these options and parameters, it is also possible to use the position parameters described above, but after you get the positional parameters, you have to make a lot of conditional judgments, because the options may be in different order

appear at different locations in the command line, and the situation is very complex. To solve this problem, you can change the built-in command getopts that bash provides.

The getopts syntax is as follows:

getopts option line option variable

Where the option line is composed of a single character of each option, as described in the preceding example for 3 options, can be combined into "U:ah"

If an option character is followed by ":" Then it means that the option needs to provide a parameter, as there is ":" Behind U.

If the script is executed with no additional parameters behind the option U, then bash will display an error message "option requires an argument--u".

If you do not want this error message, you can add ":" to the front of the option line, such as ": U:ah" like this, you do not have parameters behind the error.

The function of the option variable is:

Getopts gets the option from the command line, puts it in the options variable, and if the option requires additional arguments, the value of the parameter is placed in the variable Optarg.

Example:

[[email protected] ~]#./OPT.SH-A provides options A[[email protected] ~]#./OPT.SH-H provides options H[[email protected] ~]#./OPT.SH-A-H provides options A offers options H[[email protected] ~]#./opt.sh-u./opt.sh:option requires an argument-U[[email protected] ~]#./opt.sh-u Hell o provides options-u and Parameters: Hello[[email protected] ~]# cat opt.sh #!/bin/bash#while getopts u:ah optdo case $opt in U) echo "provides options-U and Parameter  Number: $OPTARG ";;  A) echo "provides option a";;  h) echo "offers option H";;  *)    ;; Esacdone[[email protected] ~]#

Iv. building a library of functions

If some functions often appear in the script of the design, consider extracting these functions into a single file, but this file is called a function library.

When you name a function, the first character of the function name uses _ (underscore), which typically represents the function or variable name used by the system.

Set up the function library in/tmp mylib1.sh

_getip ()

{

Local tmp R IP #函数内部使用的变量设为私有

[-Z ' $ '] && return #如果位置参数 $ null to exit directly

Shuzu= () #建立数组变量shuzu, as a return IP string, the initial value is set to an empty array

tmp=$ (ifconfig $ | grep ' inet addr ')

R=${tmp/inet addr:/}

ip=${r/bcast*/}

shuzu= ($IP) #将找到的ip设为第一个数组元素, as the return value of the result of the function processing

}

Call the syntax of the function database. /path/function database. Also use source to represent

#!/bin/bash

mylib_dir= "/tmp" #设置函数库默认路径

if [!-d "Mylib_dir"];then

Mylib_dir= "." #如果默认路径不存在就设为当前目录

Fi

. $MYLIB _dir/mylib1.sh #调用函数库mylib1. Sh

_getip eth0 #执行_getip传入的参数是网络接口的名称eth0

Ip=${shuzu[0]} #取出代表函数执行结果的数组变量shuzu的第一个元素, set the value to the variable IP

If [-N ' $ip '];then #判断 $ip is empty,-Z is empty-n is not empty

echo "Host IP Yes: $ip"

Else

echo "IP not Found"

Fi

This article is from the "Welcome to Linux World" blog, so be sure to keep this source http://linuxnote.blog.51cto.com/9876511/1641215

The seven-function application of Linux shell

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.