摘要:
定义函数、函数文件、函数调用、载入和删除函数、参数传递、函数返回状态
6.1函数定义
shell允许将一组命令集或语句形成一个可用块,这些块称为shell函数
定义函数的格式为:
函数名 ()
{
命令1
。。
}
function 函数名 ()
{
。。。
}
函数可以放在同一个文件中作为一段代码,也可以放在只包含函数的单独文件中。
<pre name="code" class="plain">#!/bin/bash
#hellofun
hello ()
{
echo "hello,today is `date`"
return 1
}
函数的调用
#!/bin/bash
#hellofun
hello ()
{
echo "hello,today is `date`"
}
echo "now going to the function hello"
hello
echo "back from the function"
6.2参数传递
向参数传递参数就像在脚本中使用位置变量$1,$2,...$9
#!/bin/bash
#hellofun
hello ()
{
echo "hello,$1 today is `date`"
}
echo "now going to the function hello"
hello cyf
echo "back from the function"
6.3函数文件
1 #!/bin/bash
2 #cyf
3 #source function
4 . hellofun
5 echo "now going to the function hello"
6 hello
7 echo "back from the function "
1 #!/bin/bash
2 #hellofun
3 hello ()
4 {
5 echo "hello,today is `date`"
6 return 1
7 }
6.4检查载入函数和删除函数
查看载入函数
-set
删除函数
unset
6.6函数返回状态值
1 #!/bin/bash
2 #hellofun
3 hello ()
4 {
5 echo "hello,today is `date`"
6 return 1
7 }
1 #!/bin/bash
2 #cyf
3 #source function
4 . hellofun
5 set
6 echo "now going to the function hello"
7 hello
8 echo $?
9 echo "back from the function "