Wu Yuxiong - born naturally ShellX study notes: Shell function

linux shell can be user-defined functions, then you can easily call in a shell script. 
the shell define the format function is as follows: 
[function] funname [()] 
{ 
    Action; 
    [ return int;] 
} 
Note:
 1 , can take function fun () is defined, may be directly fun () is defined, without any parameters.
2, return parameter can be displayed add: return returned, if not, will last a result of that command, as a return value. followed by the return value of n (0-255 
The following example defines a function and call: 

# ! / bin / the bash 
demoFun () { 
    echo " this is my first shell function! " 
} 
echo " ----- function started ----- " 
demoFun 
echo " ----- ----- function is finished " 

output:
 ----- begin ----- function
This is my first shell function!
 ----- ----- function completes
: The following function definition with a return statement
 # / bin / the bash! 
FunWithReturn () { 
    echo " two digital input function will be an addition operation ... " 
    echo " enter the first number: " 
    Read ANUM 
    echo " enter the second number: " 
    the Read anotherNum 
    echo " two figures were $ aNum anotherNum and $! " 
    return $ (($ aNum + $ anotherNum)) 
} 
funWithReturn 
echo " two digital inputs for the sum of $?! " 
output similar to the following: 
the two functions will inputted digital addition operation ... 
enter the first digit:
 1 
enter the second number:
 2 
two digits are 1 and 2 !
Two numbers for the inputs and 3 ! 
Function return value after calling the function through $? Be obtained. 
Note: All functions must be defined before use. This means that the function must be placed in the beginning of the script until the shell interpreter when it was first discovered, it can be used. Call functions using only its function name.
Function parameters 
in the Shell, the parameters that can be passed when calling the function. Inside the function thereof, to obtain the value of the parameter $ n the form of, e.g., $ 1 represents the first parameter, the second parameter represents $ 2 ... 
sample function with parameters: 
# ! / Bin / the bash 
funWithParam () { 
    echo " first parameter. 1 $! " 
    echo " The second parameter is 2 $! " 
    echo " 10th parameter 10 to $! " 
    echo " 10th parameter is {10} $! " 
    echo " eleventh parameter . 11} is {$! " 
    echo " number of parameters for # $! " 
    echo " a string of all output parameters as $ *! "
1 ! 
The second parameter is 2 ! 
10th parameter is 10 ! 
10th parameter is 34 ! 
Eleventh parameter 73 ! 
Total number of parameters . 11 a! 
As a string of all output parameters 123456 7893473 ! 

Note, $ 10 10th parameter can not be obtained, obtain parameters required tenth {10} $. When n> = 10, requires the use of $ {n} to obtain the parameters.

 

Guess you like

Origin www.cnblogs.com/tszr/p/12111943.html