1、函数的使用
函数是一个脚本代码块,你可以对它进行自定义命名,并且可以在脚本中任意位置使用这个函数,要使用这个函数,只要使用这个函数名称就可以了。使用函数的好处:模块化,代码可读性强。
(1)函数创建语法
方法 1:
function name {
commands
}
注:name 是函数唯一的名称
方法 2:name 后面的括号表示你正在定义一个函数
name(){
commands
}
调用函数语法:
函数名 参数 1 参数 2 …
调用函数时,可以传递参数。在函数中用$1、$2…来引用传递的参数
(2)函数的使用
实例1:
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
echo "test function"
} #以上内容定义函数
test #调用函数
[root@test shell]# sh fun.sh
test function
[root@test shell]#
注:函数名的使用,如果在一个脚本中定义了重复的函数名,那么以最后一个为准。
举例:
[root@test shell]# sh fun.sh
test function
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
echo "test function one"
}
function test {
echo "test function two"
}
test
[root@test shell]# sh fun.sh
test function two
[root@test shell]#
(3)返回值
使用 return 命令来退出函数并返回特定的退出码。
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
echo "test function one"
ls /home
return 2
}
test
[root@test shell]# sh fun.sh
test function one
1.txt YDSOC_C4I_SYSLOG YDSOC_C4I_SYSLOG_20201009.tar.gz aa bb cc client111.crt client111.csr client111.key test1
[root@test shell]# echo $?
2 #返回值,为指定返回值
注:状态码的确定必需要在函数一结束就运行 return 返回值;状态码的取值范围(0~255)。
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
echo "test function one"
ls /home
return 2
ls /root
}
test
[root@test shell]# sh fun.sh
test function one
1.txt YDSOC_C4I_SYSLOG YDSOC_C4I_SYSLOG_20201009.tar.gz aa bb cc client111.crt client111.csr client111.key test1
[root@test shell]# echo $?
2
[root@test shell]#
注:return 只是在函数最后添加一行,然后返回数字,只能让函数后面的命令不执行,无法强制退出整个脚本。exit 整个脚本就直接退出。
(4)将函数赋值给变量
函数名相当于一个命令。
[root@test shell]# cat fun.sh
#!/bin/bash
function test {
read -p "输入一个整数:" int
echo $[ $int+1 ]
}
sum=$(test)
echo "result is $sum"
[root@test shell]# sh fun.sh
输入一个整数:1
result is 2
[root@test shell]#
(5)函数参数传递
实例1:通过脚本传递参数给函数中的位置参数$1
[root@test shell]# cat fun.sh
#!/bin/bash
function test {
rm -rf $1
}
test $1
[root@test shell]# touch 1.txt
[root@test shell]# ls
1.txt fun.sh
[root@test shell]# sh fun.sh 1.txt
[root@test shell]# ls
fun.sh
[root@test shell]#
实例2:调用函数时直接传递参数
[root@test shell]# touch /home/test.txt
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
rm -rf $1
}
test /home/test.txt
[root@test shell]# ls /home
test.txt
[root@test shell]# sh fun.sh
[root@test shell]# ls /home
[root@test shell]#
实例3:函数中多参数传递
[root@test shell]# vi fun.sh
#!/bin/bash
function test {
rm -rf $1
rm -rf $2
}
test /home/test1 /home/test2
[root@test shell]# touch /home/test{1,2}
[root@test shell]# ls /home
test1 test2
[root@test shell]# sh fun.sh
[root@test shell]# ls /home
[root@test shell]#
(6)函数中变量处理
函数使用的变量类型有两种:
局部变量、全局变量。
全局变量,默认情况下,你在脚本中定义的变量都是全局变量,你在函数外面定义的变量在函数内也可以使用。
[root@test shell]# cat fun.sh
#!/bin/bash
function test {
num=$[var*2]
}
read -p "input a num:" var
test
echo the new value is: $num
[root@test shell]# sh fun.sh
input a num:1
the new value is: 2
[root@test shell]#
个人公众号,微信搜索:linux言叙