I. DEFINITION of format
[Function] Function name ()
{
Command table
}
Ii. Method of Invocation
First define, then use, direct input function name, no parentheses required ()
Three, function parameter transfer method
Can be passed using positional parameters or variables
#!/bin/bash
# myfirst.sh
testfunction () {echo"$1,$2" #positional parameter passing parametersEcho"$val 1, $val 2" #Variable pass parameter}val1="test1"Val2="test2"testfunction1 2#calling FunctionsEcho"$1,$2" #positional parameters passed when printing a call script
Operation Result:
[[email protected] shell] # ./myfirst.sh a btest1,test2a,b
Iv. return
Normally, after the last command of a function executes, it exits the function, but you can also exit the function immediately with the return command
return [n]
Where the n value is the exit value when the Exit function is exited, but the N value defaults to the exit value when the last command exits
How far shell scripts can contain multiple functions
#!/bin/bash
# myfirst2.sh
TestFunction1 () {echo"$1,$2" return1Echo"$val 1, $val 2"}val1="test1"Val2="test2"TestFunction11 2#call the first functionEcho"$?" #print out the exit value of the function TestFunction1Echo"$1,$2"TestFunction2 () {echo"This is fun2" return2Echo"Test"}testfunction2#call a second functionEcho"$?" #print out the exit value of TestFunction2
Operation Result:
[[email protected] shell] # ./myfirst2.sh a b1,21a,bthis is fun22
Vi. Summary
Functions in the shell can assemble several commands together, call through a function name, and make repeated calls to enhance the reuse of the script.
Shell Scripting Learning notes--functions