Application [Shell] Function

Definition Format the shell functions as follows:

[ Function ] funname [()]

{

    action;

    [return int;]

}
 

Description:

  • 1, can function with 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

for example:

Without function parameters:

demoFunc () {# defined function
         echo  " This is the first function of a shell "
}

echo  " ------- ------ function started ."
demoFunc # execution function
echo  " ------- ------ function is finished ."

Implementation of the results:

$ SH testFunc. SH  
------- ------ function begins execution
This is the first one shell functions
------ ------- function completes

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 with multiple return values:

Test () {
 echo  100 # returns 100
 echo  200 # 200 returns
}

a=$(test)
echo $a

Implementation of the results:

sh testfunc.sh 
100 200

 Function with parameters: 

funWithParam () {
     echo  " first parameter. 1 $! " 
    echo  " The second parameter is the $ 2! "
}

funWithParam 1 2

Implementation of the results:

SH testFunc. SH 
first parameter is 1 ! 
The second argument is 2 !

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

In addition, there are several parameters to handle special characters:

Parameter Handling Explanation
$# The number of arguments passed to the script or function
$* Show all parameters passed to the script to a single string
$$ The script runs the current process ID number
$! Finally, a process running in the background ID number
$@ $ * The same, but the use of quotation marks, and returns each parameter in quotation marks.
$- Shell used to display the current option, and set the same command function.
$? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。

 

参考文档:

Shell 函数

Shell函数返回多个值

Guess you like

Origin www.cnblogs.com/kaerxifa/p/12187897.html