【shell】函数

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://wanderer-zjhit.blogbus.com/logs/158596008.html

shell中允许将一组命令集或语句形成块结构,称为函数,函数有两种实现方式:
1. 可以将所有的函数实现为库,然后在每个调用的脚本中用. 库路径来引用该库中所有函数;
2. 另一种是将当前脚本中的一部分处理语句块以函数形式完成,在其后以fun arg1 arg2等形式引用。

函数传参问题与脚本传参类似:
1. 局部与脚本的函数可以直接修改shell中的变量值
2. 库函数只能通过echo $a将值以字符串形式返回,再在脚本中分解

1 函数定义格式
#!/bin/bash
function fun1_name()
{  
  command1-1
  ...
  command1-n
}
function fun2_name()
{  
  command2-1
  ...
  command2-n
}
注:
1 函数可以同一定义在一个shell文件中,函数库的实现:
[root@wzp ~]# cat funcs 
function ceo() {
  echo $[ $1 + $2 ]
}
function cfo () {
  echo $[ $1 * $2 ]
}
然后在其他shell脚本中有两种调用方式:

1-1 传统的方式:在当前shell脚本中直接 . ./fun.sh引用函数实现脚本,在之后直接调用其中函数
调用库:
[root@wzp ~]# cat 7.41test 
#!/bin/bash
. ./funcs  引用库
注:调用./funcs不可以,该表达式会调用另一个进程执行./funcs,当前进程不会得到函数信息
result=`ceo 12 24`
echo "the result is $result"
[root@wzp ~]# cat 7.42test 
#!/bin/bash
. ./funcs
result=`cfo 12 5`
echo "the result is $result"
[root@wzp ~]# ./7.41test 
the result is 36
[root@wzp ~]# ./7.42test 
the result is 60

1-2 在.bashrc文件中利用. function.sh命令将shell文件中的所有函数导入到当前shell环境变量中,也可以在bash命令行下利用. function.sh导入。将shell函数导出到shell环境中后,可以直接在其他shell中调用该函数,而不是通过c语言那样通过头文件形式完成
[root@wzp ~]#. ./func  在命令行下用该命令加载到shell环境变量中,用set可以查看,用unset fun删除
[root@wzp ~]#ceo 12 24 
[root@wzp ~]#the results is 36
1.3 在引用函数库的情况下,shell脚本要获得shell库函数的返回值,需要:函数通过echo $x输出一个值,该值可以通过在shell中调用ret=`fun arg1 arg2`等形式接受到
[root@wzp ~]# cat funcs  定义库
function ceo() {
  echo $[ $1 + $2 ]
}
[root@wzp ~]# cat 7.41test  使用库并获取返回值
#!/bin/bash
. ./funcs
result=`ceo 12 24`
echo "the result is $result"

2 当然也可以在前面定义函数fun,直接在后面利用fun x y z调用fun函数完成
注:此时可以共享同一shell脚本中的全局变量,函数内部的局部变量不会传递到shell文件中,此时可以利用return 0|1 返回有特定意义的值
[root@wzp ~]# cat 7.3test 
#!/bin/bash
function cfo {
local temp=$[ $value + 5 ]  只要不用local关键字在函数中限定,默认定义的所有变量都是全局的
result=$[ $temp + 2 ]
}
temp=8  全局变量
value=10
cfo       调用函数
echo "the result is $result"
if [ $temp -gt $value ]  temp取全局变量8,value却全局变量10
then
   echo "temp is larger"
   echo "temp=$temp ; result=$result"
else
   echo "temp is smaller"
   echo "temp=$temp ; result=$result"
fi
[root@wzp ~]# ./7.3test 
the result is 17
temp is smaller
temp=8 ; result=17
我只是多加了两个echo "temp=$temp ; result=$result",就为了把temp和result这两个变量显示出来,我们看到,执行函数后,temp的值没变,因为函数中局部定义了temp,所以还是8;可是value的值通过函数运算后是有效生成的,所以附加后是17。

3 每个函数在定义时候不添加形参,可以使用$#,$1,$2等接受shell输入参数,在调用时候用fun2_name x y z将实参传递过去。见上例


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值