Skip to content

Commit d7fd921

Browse files
committed
docs: add function
1 parent 1d5a8f6 commit d7fd921

1 file changed

Lines changed: 97 additions & 0 deletions

File tree

docs/function.md

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# 函数
2+
3+
## 基本用法
4+
5+
函数是一段可以重复执行的代码。
6+
7+
下面是定义函数的语法。
8+
9+
```bash
10+
function function_name {
11+
echo "Hello, World"
12+
}
13+
```
14+
15+
使用时,直接写函数名即可。
16+
17+
```bash
18+
$ function_name
19+
```
20+
21+
如果有参数,就跟在函数名后面。
22+
23+
```bash
24+
$ function_name arg1 arg2 arg3
25+
```
26+
27+
下面是脚本里面定义函数并调用的例子。
28+
29+
```bash
30+
#! /bin/bash
31+
function print_msg {
32+
echo "Hello, World"
33+
}
34+
print_msg
35+
```
36+
37+
定义函数以后,脚本要加上可执行属性。
38+
39+
```bash
40+
$ chmod +x function.sh
41+
$ ./function.sh
42+
Hello, World
43+
```
44+
45+
## 参数
46+
47+
函数体内部使用`$`作为参数的前缀,比如`$1`就表示第一个参数,`$2`就表示第二个参数,以此类推。
48+
49+
```bash
50+
function print_msg {
51+
echo "Hello $1"
52+
}
53+
```
54+
55+
上面代码中,`$1`表示第一个参数。
56+
57+
```bash
58+
$ print_msg world
59+
Hello world
60+
```
61+
62+
下面是一个日志函数的例子。
63+
64+
```bash
65+
function log_msg {
66+
echo "[`date '+ %F %T'` ]: $@"
67+
}
68+
```
69+
70+
使用方法如下。
71+
72+
```bash
73+
$ log_msg "This is sample log message"
74+
[ 2018-08-16 19:56:34 ]: This is sample log message
75+
```
76+
77+
## 返回值
78+
79+
`return`命令用于从函数返回一个值。
80+
81+
```bash
82+
function func_return_value {
83+
return 10
84+
}
85+
```
86+
87+
函数将返回值返回给调用者。如果命令行直接执行函数,下一个命令可以用`$?`拿到返回值。
88+
89+
```bash
90+
$ func_return_value
91+
$ echo "Value returned by function is: $?"
92+
Value returned by function is: 10
93+
```
94+
95+
## 参考链接
96+
97+
- [How to define and use functions in Linux Shell Script](https://www.linuxtechi.com/define-use-functions-linux-shell-script/), by Pradeep Kumar

0 commit comments

Comments
 (0)