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:
[SQL]View PlainCopy
- function-name () {
- Command1
- ........
- }
Or
[Plain]View PlainCopy
- #函数名前面也可以加上function关键字
- function Function-name () {
- Command1
- ........
- }
2. Function calls
The following is a script instance of a function:
[HTML]View PlainCopy
- #!/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:
[HTML]View PlainCopy
- #!/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:
[HTML]View PlainCopy
- #!/bin/bash
- function Hello () {
- echo "Hello!"
- Return 1
- }
The Hellofunction file above is a function file that can be called from another script
[HTML]View PlainCopy
- #!/bin/bash
- . Hellofunction #调用函数文件, there's a space between the dots and the hellofunction.
- Hello #调用函数
5. Loading and deleting
To view loaded functions with Set
Cancel loading with unset function-name
Examples are as follows:
[HTML]View PlainCopy
- #!/bin/bash
- #hellof
- . Hellofunction
- unset Hello
- Hello #因为已经取消载入, so it goes wrong
How shell scripts Customize functions