shell-defined functions

Shell function syntax is defined as follows:

function name() {

    statements

    [return value]

}

A description of each section:

Shell keywords function is specifically added to function;

name is the name of the function;

statements is the code for the function to be executed, that is, a set of statements;

return value represents the return value of the function, which is the Shell return key, specifically used in the function returns a value; this part can not write can be written.

{} Part surrounded by the body of the function is called, calling a function, the function is actually execute the code body.

Function definition simplified wording

You can not write function key if you find it troublesome, the function definition:

name() {

    statements

    [return value]

}

If you write a function keyword, you can omit the parentheses after the function name:

function name {

    statements

    [return value]

}

I recommend using standard wording, this can be done "to see to know the name meaning" one can understand.

Function call

Can pass parameters to it when calling the Shell function, you can not pass. If you do not pass parameters given directly to the function name:

name

If the parameter passed, then separated by spaces between a plurality of parameters:

name param1 param2 param3

Whatever the form, the function does not need parentheses after his name.

And other programming languages ​​are different, not indicate Shell function defining parameters, the parameters can be passed Shique call, and passing it what parameters any parameters it received.

Shell is not limited by the order to define and call, you can define the front on the call, you can turn, will be defined later in the call.

Examples of presentation

1) the definition of a function, the output address Shell tutorial:

image.png

#!/bin/bash

# Function definition

function url(){

echo "http://c.biancheng.net/shell/"

}

# Function call

url

operation result:

image.png

http://c.biancheng.net/shell/

You can call in front of the definition, which is written as follows :

image.png

#!/bin/bash

# Function call

url

# Function definition

function url(){

echo "http://c.biancheng.net/shell/"

}

2) definition of a function, and calculate all parameters:

image.png

#!/bin/bash

function getsum(){

local sum=0

for n in $@

do

((sum+=n))

done

return $sum

}

getsum 10 20 55 15 #调用函数并传递参数

echo $?

运行结果:

image.png

100

Guess you like

Origin blog.51cto.com/14451009/2441623