函数是一个脚本代码块,你能够对它进行自定义命名,而且能够在脚本中任意位置使用这个函数,要使用这个函数,只要使用这个函数名称就能够了。使用函数的好处:模块化,代码可读性强。shell
function name { commands }
注:name 是函数惟一的名称bash
name( ){ commands }
调用函数语法:ide
函数名 参数 1 参数 2 …模块化
调用函数时,能够传递参数。在函数中用$一、$2…来引用传递的参数函数
[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]#
注:函数名的使用,若是在一个脚本中定义了重复的函数名,那么以最后一个为准。spa
[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]#
使用 return 命令来退出函数并返回特定的退出码。input
[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 #返回值,为指定返回值it
注:状态码的肯定必须要在函数一结束就运行 return 返回值;状态码的取值范围(0~255)。 io
[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 整个脚本就直接退出。function
函数名至关于一个命令。
[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]#
[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]#
[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]#
[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]#
函数使用的变量类型有两种:
局部变量、全局变量。
全局变量,默认状况下,你在脚本中定义的变量都是全局变量,你在函数外面定义的变量在函数内也能够使用。
[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]#
我的公众号: