设为首页 收藏本站
查看: 797|回复: 0

shell 函数

[复制链接]

尚未签到

发表于 2015-12-3 14:52:02 | 显示全部楼层 |阅读模式
1 shell函数的定义及其调用
  shell函数有两种格式

  function name {
  commands
  }

  name() {
  commands
  }

  其中,name为函数名,commands为函数体中执行的语句块。定义函数后,可以简单地通过函数名name对其进行调用。
  注:
  如果出现两个同名的函数定义,那么后者会覆盖前者,而不是报错。

  

2 函数返回值
  shell函数在运行结束时返回状态码,有三种方式:

  1 默认情况下,返回函数中最后一条命令的状态码,可以用$?来获取函数的退出状态码




#! /bin/bash
# testing the exit status of a function
#
function func1 {
echo "This is the first form of defining a function:"
ls -l badfile   # badfile is not exist
}
func2() {
echo "This is the second form of defining a function:"
date            #
}
echo "Testing the function and exit status"
echo
func1
echo "The exit status of func1 is: $?"
echo
func2
echo "The exit status of func2 is: $?"
[iyunv@benxintuzi shell]# ./35.sh
Testing the function and exit status
This is the first form of defining a function:
ls: cannot access badfile: No such file or directory
The exit status of func1 is: 2
This is the second form of defining a function:
Tue Aug 11 22:43:48 PDT 2015
The exit status of func2 is: 0

  2 使用return命令可以返回0~255之间的任意值




#! /bin/bash
# testing the exit status of a function
#
func() {
read -p "Please enter a value: " value
echo "doubling the input value..."
return $[ $value * 2 ]
}
func
echo "The exit status of func is: $?"
[iyunv@benxintuzi shell]# ./36.sh
Please enter a value: 50
doubling the input value...
The exit status of func is: 100
[iyunv@benxintuzi shell]# ./36.sh
Please enter a value: 200
doubling the input value...
The exit status of func is: 144

  3 使用变量保存,这种方式不仅可以返回任意数值,还可以返回字符串值




#! /bin/bash
# testing the exit status of a function
#
func() {
read -p "Please enter a value: " value
echo $[ $value * 2 ]
echo "hello, I come"
}
result=`func`
echo "The exit status of func is: $result"
[iyunv@benxintuzi shell]# ./37.sh
Please enter a value: 500
The exit status of func is: 1000
hello, I come

  

3 函数参数



函数可以利用标准的环境变量参数,$0表示函数名,$1表示第一个参数,$2表示第二个参数,...,$#表示参数个数。
#! /bin/bash
# access script parameters inside a function
#
func() {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ]
then
value=`func $1 $2`
echo "The result is $value"
else
echo "Usage: func a b"
fi
[iyunv@benxintuzi shell]# ./38.sh 55 66
The result is 3630

  

4 函数变量
  包括全局变量与局部变量。默认情况下,在shell中定义的任何变量都是全局变量。如果在变量定义前加上local关键字就变为局部变量了,如:local temp。



#! /bin/bash
# local and global variable
#
func() {
local temp=$[ $value + 5 ]
result=$[ $temp * 2 ]
}
value=10
temp=20
func
echo "$temp"
echo "$result"
[iyunv@benxintuzi shell]# ./39.sh
20
30

  

5 数组变量
  数组作为函数参数:
  必须将数组变量分解为单个值,然后将这些值用作函数参数使用;在函数体中,可以将所有参数重组为新的数组变量:



#! /bin/bash
# array variable to function
func() {
local newarray
newarray=(`echo "$@"`)
echo "The new array value is: ${newarray
  • }"
    local sum=0
    for value in ${newarray
  • }
    do
    sum=$[ $sum + $value ]
    done
    echo "The sum of newarray is: $sum"
    }
    myarray=(1 2 3 4 5)
    echo "The original array is ${myarray
  • }"
    func ${myarray
  • }
    [iyunv@benxintuzi shell]# ./41.sh
    The original array is 1 2 3 4 5
    The new array value is: 1 2 3 4 5
    The sum of newarray is: 15

      
      数组作为函数返回值:



    #! /bin/bash
    # function return array
    func() {
    local oriarray
    local newarray
    local elements
    local i
    oriarray=(`echo "$@"`)
    newarray=(`echo "$@"`)
    elements=$[ $# - 1 ]
    for (( i = 0; i <= $elements; i++ ))
    {
    newarray[$i]=$[ ${oriarray[$i]} * 2 ]
    }
    echo ${newarray[*]}
    }
    myarray=(1 2 3 4 5)
    echo "The original array is ${myarray
  • }"
    arg1=`echo ${myarray
  • }`
    result=(`func $arg1`)
    echo "The new array is: ${result
  • }"
    [iyunv@benxintuzi shell]# ./42.sh
    The original array is 1 2 3 4 5
    The new array is: 2 4 6 8 10

      

    6 创建库文件
      函数库文件是为了解决不同脚本文件中使用相同函数块的问题。
      首先定义一个库文件myfuncs用来解决四则运算功能:



    [iyunv@benxintuzi shell]# cat myfuncs
    # my script functions
    addem() {
    echo $[ $1 + $2 ]
    }
    minusem() {
    echo $[ $1 - $2 ]
    }
    multiem() {
    echo $[ $1 * $2 ]
    }
    divem() {
    if [ $2 -eq 0 ]
    then
    -1
    else
    echo $[ $1 / $2 ]
    fi
    }
      然后在脚本文件中使用库文件中的函数即可,但是使用前必须使用source命令或者.命令在当前上下文环境中运行库文件:



    [iyunv@benxintuzi shell]# cat 40.sh
    #! /bin/bash
    # using functions defined in a library file
    # excute library file in the context
    . ./myfuncs     # source ./myfuncs
    value1=10
    value2=4
    result1=`addem $value1 $value2`
    result2=`minusem $value1 $value2`
    result3=`multiem $value1 $value2`
    result4=`divem $value1 $value2`
    echo "addem($value1, $value2): $result1"
    echo "minusem($value1, $value2): $result2"
    echo "multiem($value1, $value2): $result3"
    echo "divem($value1, $value2): $result4"
      执行脚本文件:



    [iyunv@benxintuzi shell]# ./40.sh
    addem(10, 4): 14
    minusem(10, 4): 6
    multiem(10, 4): 40
    divem(10, 4): 2

      

    7 在命令行中使用shell函数
      方式一:
      在命令行中直接定义一个函数:函数名及其函数体在一行内定义,不同语句之间用分号隔开:



    [iyunv@benxintuzi shell]# addem() { val1=5; val2=10; echo $[ val1 + $val2 ]; }
    [iyunv@benxintuzi shell]# addem
    15
      方式二:
      在命令行中直接定义一个函数:函数名及其函数体在多行中定义,语句末尾不用加分号:



    [iyunv@benxintuzi shell]# addem() {
    > val1=5
    > val2=10
    > echo $[ $val1 + $val2 ]
    > }
    [iyunv@benxintuzi shell]# addem
    15
      方式三:
      在.bashrc文件中定义函数:
      在命令行中直接定义的shell函数在退出shell时就丢失了,如果想使得在每次启动新shell时都定义这个函数,一个比较好的办法就是将函数定义在.bashrc文件中。
      

  • 运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-146904-1-1.html 上篇帖子: Shell 常用命令总结 下篇帖子: shell text code
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表