和其他脚本语言一样,bash同样支持函数。我们可创建特定的函数,也可以创建能够接受参数的函数。需要的时候直接调用就可以了。
1.定义函数
function fname()
{
statements;
}
或者:
fname()
{
statements;
}
只需要使用函数名,就可以调用某个函数
例如:
[root@gitlab script]# cat function_test.sh
#!/bin/bash
function fname()
{
echo "This is test function"; #;也可不用
}
for i in {1..5}
do
fname; #调用函数 ;也可不用
done
[root@gitlab script]# ./function_test.sh
This is test function
This is test function
This is test function
This is test function
This is test function
2.函数传参
[root@gitlab script]# cat function_test.sh
#!/bin/bash
function fname()
{
echo $1 $2 #打印参数
echo "$@" #以列表的方式一次性打印所有参数
echo "$*" #类似于$@,但单数被作为单个实体
}
fname hello world #传参
echo "##########################"
fname 1 2
[root@gitlab script]# ./function_test.sh
hello world
hello world
hello world
##########################
1 2
1 2
1 2