盒子
盒子
文章目录
  1. 1. 定义函数

Shell 脚本编程(高级)

1. 定义函数

函数是可以起个名字并在代码中任何位置重用的代码块。你要在脚本中使用该代码块时,只要使用分配的函数名就行了。

注意

  • 函数定义要在使用函数前;
  • 如果你重定义了函数,新定义的会覆盖原来函数的定义,而不会产生任何错误信息;
  • 默认情况下,函数的退出状态码是函数中最后一条命令返回的退出状态码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#! /bin/bash
function hello { # 函数名和花括号之间必须加入空格,否则报错
echo "Hello World!"
}

function example2 {
echo "example 2"
}

for ((a=1; a<10; a++))
do
hello # 注意函数定义要在使用函数前
example2
done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[root@master01 scripts]# ./function_demo1 
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
Hello World!
example 2
支持一下
扫一扫,支持forsigner
  • 微信扫一扫
  • 支付宝扫一扫