一、函数的定义
函数可以放在同一个文件中作为一段代码,也可以放在只包含函数的单独文件中:#!/bin/bash
#hello-fun
function hello()
{
echo "hello,today is `date`"
return 1
}
二、函数的调用#!/bin/bash
#func
function hello()
{
echo "hello,today is `date`"
}
echo "now going to the function helo()"
hello #直接写函数文件名进行函数调用
echo "back from the hell()"
三、参数的传递#!/bin/bash
#func
function hello()
{
echo "hello $1"
}
echo "now going to the function helo()"
hello argument-1 # argument-1 是 $1
echo "back from the hello()"
四、从另外的文件中调用函数
主脚本文件:
#!/bin/bash
#func
#source function
. hellofun # hellofun 文件里有需要调用的函数
echo "now going to the function hello"
hello
echo "back from the function"
函数文件:
#!/bin/bash
#hellofun
functon hello()
{
echo hello, today is `date`
return 1
}
查看载入函数: set
删除函数 : unset
五、函数的返回值
函数文件:
#!/bin/bash
#hellofunctions
function hello()
{
echo "hello,today is `date`"
return 0
}
shell 程序文件:
#!/bin/bash
#func
. hellofunctions # include 函数文件
echo "now going to the function hello"
hello
echo $? # 特殊变量 $? 得到返回值
echo "back from the function"
注: shell 函数不像其他语言的函数,可以带回返回值然后赋给变量(通过 $? 变量),比如:
[Bash shell] 纯文本查看 复制代码 #!/bin/sh
function myfunc() {
echo "return a value"
return 2
}
myfunc
ret=$?
echo $ret
运行输出:[beyes@beyes command]$ sh tmp.sh
return a value
2 注意,获取返回值,不能直接将函数赋值给变量,如上面的不能写成 ret=`myfunc` ,然后觉得 $ret 的值为 2 ,而是需要用 $? 变量进行赋值。 |