Description of function definition formats, function parameters, and Shell functions
You can use shell to define a function, and then use it in a shell script. The Function Definition Format in shell is as follows:
[ function ] funname [()]{ action; [return int;]}
Function fun () or fun () can be defined without any parameters. If the parameter is returned, the result of the last command is used as the return value. Return followed by the value n (0-255)
Return not included
demoFun(){ echo "This is my first function"}echo "-----func start-----"demoFunecho "-----func end-----"
Include return
funWithReturn(){ echo "add action" echo "input first num: " read aNum echo "input second num: " read anotherNum echo "The two nums are $aNum and $anotherNum !" return $(($aNum+$anotherNum))}funWithReturnecho "The total of two nums are $? "
The Return Value of the function is $? .
Note: All functions must be defined before use. This means that the function must be placed at the beginning of the script until the shell interpreter discovers it for the first time. Only the function name can be used to call a function.
Function Parameters
In Shell, parameters can be passed to a function. Inside the function body, get the parameter value in the form of $ n. For example, $1 indicates the first parameter, and $2 indicates the second parameter ......
funWithParam(){ echo "first : $1 " echo "second : $2 " echo "tenth : $10 " echo "tenth : ${10} " echo "eleventh : ${11} " echo "total num : $# " echo "the single string : $* "}funWithParam 1 2 3 4 5 6 7 8 9 34 73
Note: $10 cannot obtain the tenth parameter. $ {10} is required to obtain the tenth parameter }. When n> = 10, you need to use $ {n} to obtain the parameter.