Functions are often used when writing programs, and general development tools have a rich library of functions. But sometimes you need to customize the function to meet our needs.
In Linux, the same is true for shell scripts, which sometimes use custom functions.
The simplest definition of a function is a set of command sets or statements that form an available block called a function.
1. Define the format of the function:
Function-name () { Command1 ... }
Or
#函数名前面也可以加上function关键字function Function-name () { Command1 ... }
2. Function calls
The following is a script instance of a function:
#!/bin/bash function Hello () { #声明函数 echo "hello!" #函数的主体, Output "hello!" } #函数结束 Hello #调用函数
3. Parameter passing
passing arguments to a function is like using a variable location in a script $1,$2,$3...$9
The following is an instance of a passing parameter:
#!/bin/bash function Hello () { echo ' hello! The first parameter is ' $ '. " } Hello good
#该脚本执行的结果是: hello! The first parameter is ' good '.
4. function files
Save the file of the function, write a function file with the above example as follows:
#!/bin/bash function Hello () { echo "hello!" Return 1 }
The Hellofunction file above is a function file that can be called from another script
#!/bin/bash . hellofunction #调用函数文件, there is a space between the point and the hellofunction Hello #调用函数
5. Loading and deleting
to view loaded functions with Set
Cancel loading with unset function-name
Examples are as follows:
#!/bin/bash #hellof . hellofunction unset Hello Hello #因为已经取消载入, so there will be an error
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Custom functions in shell scripts