Shell--函数

1、定义格式:
function  functionName()      #关键字function可以省略
{
    list of commands
    [return value]
}
  函数返回值:                          #函数的返回值只能是整数
可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

eg:
  1. #!/bin/bash
  2. funWithReturn(){
  3. echo -n "Input first number: "
  4. read aNum
  5. echo -n "Input another number: "
  6. read anotherNum
  7. echo "The two numbers are $aNum and $anotherNum !"
  8. return $(($aNum+$anotherNum))
  9. }
  10. funWithReturn      #调用函数funWithReturn
  11. ret=$?          #读取返回值
  12. echo "The sum of two numbers is $ret !"
 
2、带参函数
特殊变量:
$#传递给函数的参数个数。
$*显示所有传递给函数的参数。
$@与$*相同,但是略有区别
$?函数的返回值。
eg:
  1. #!/bin/bash
  2. funWithParam(){
  3. echo "The value of the first parameter is $1 !"
  4. echo "The value of the second parameter is $2 !"
  5. echo "The value of the tenth parameter is $10 !"
  6. echo "The value of the tenth parameter is ${10} !"
  7. echo "The value of the eleventh parameter is ${11} !"
  8. echo "The amount of the parameters is $# !" # 参数个数
  9. echo "The string of the parameters is $* !" # 传递给函数的所有参数
  10. }
  11.  
  12. funWithParam 1 2 3 4 5 6 7 8 9 34 73 #参数之间以空格区分

3、删除函数
$unset  .f  functionName 

4、文件包含
在一个脚本文件中调用另一个脚本文件(被调用的shell脚本可以没有执行权限)
.空格fileName
eg:    . /home/text.sh

source空格fileName
eg:   source /home/text.sh

这样就可以调用另一个脚本中的函数或者变量了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值