Shell function of


  Shell is a function of the nature of some script code can be reused, this code is written well in advance and put in the specified location, you can use the direct retrieval. Shell is similar in function and C ++, Java, Python, C # and other programming languages ​​function, but some differences in syntax details.


Function definition

Shell function syntax is defined as follows:

function name() {
[return value]



  • 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.


Shorthand function

You can not write function key if you find it troublesome function is defined as follows:

name() {
[return value]


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

function name {
[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



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 must first define and then call the function, and other languages ​​are not the same.



#! / bin / the bash 
function GetSum () { 
    local SUM = 0 
    for n- in $ @
         (( SUM + = n-))
    return $ SUM 

GetSum 10 55 15 # 20 is calling a function and passing parameters
echo $?

Guess you like