1. 在写shell脚本时,很多的地方使用了同一段代码,在shell脚本中多次重写大块代码段太累,bash shell提供了用户自定义函数功能可以解决这个问题,可以将shell代码放进函数中封装起来,这样能在脚本中的任何地方多次使用,下面来创建一个脚本函数。函数是代码块,在脚本中使用代码块,只要使用函数名字就行了,(这个过程称为调用函数)。
2. 创建函数的两种格式
第一种格式,采用关键字function,后跟分配给该代码的函数名
function name {
commands1
commands2
}
name属性定义了函数的唯一的名称,脚本中定义的每个函数必须有一个唯一的名称。
comands是构成函数的一条或多条bash shell命令,在函数调用时,bash shell会按命令函数中出现的顺序依次执行,就像普通脚本中一样。
第二种格式,函数名后的空括号表明正在定义一个函数,
name () {
comands
}
3.使用函数,
要在脚本中使用函数,只需要像其他shell命令一样,在行中指定函数名字就行了
复制代码:
#/bin/bash
#a function in a script
function func1 { #关键字function后定义函数名func1
echo "This is an example of a function" #定义内容是echo后面显示的内容
}
count=1 #定义变量count给赋值1
while [ $count -le 3 ] #定义wehile的条件,conunt值小于3
do
func1 #调用函数func1,显示函数内容
count=$[ $count + 1 ] #显示3次
done
echo "This is the end of the loop" #echo显示字符串
func1 #再次调用函数func1
echo "Now this the end of the script" #echo显示字符串
[root@smart 桌面]# ./function.sh 执行结果
This is an example of a function #显示函数内容1次
This is an example of a function #显示函数内容2次
This is an example of a function #显示函数内容3次
This is the end of the loop #echo显示字符串
This is an example of a function #再次调用函数func1
Now this the end of the script #echo显示字符串