zoukankan      html  css  js  c++  java
  • Linux 函数的使用

    注意点:
    1、函数名必须是唯一的
    2、如果重定义了函数,新定义会覆盖原来函数的定义

    一、定义函数的方式

    方法1、  

      function name {

        commands  
      }
    方法2、
    name() {
    commands
    }
     
    二、使用函数输出
      3 function dbl {
      4     read -p "Enter a value: " value
      5     echo $value
      6 #echo $[ $value * 2 ]
      7 }
      8 result=$(dbl)
      9 echo "The new value is $result"
     
    三、在函数传递参数
    方法1:传递一个
    要在函数中使用参数值,必须在调用函数时手动将它们传过去
    $ cat test
    #!/bin/bash
    # trying to access script parameters inside a function
    function func7 {
      echo $[ $1  *  $2 ]
    }
    if [ $# -eq 2 ]
    then
      value=$(func7 $1 $2)
      echo "The result is $value"
    else
      echo "Usage: badtest1 a b"
    fi
    方法2:传递数组
      1 #!/bin/bash
      2 function testit {
      3     local newarray
      4     newarray=($(echo "$@"))
      5     echo "The new array value is: ${newarray[*]}"
      6 }
      7 myarray=(1 2 3 4 5)
      8 echo "The original array is ${myarray[*]}"
      9 testit ${myarray[*]}
    [Linux_test]$ ./aaa.sh
    The original array is 1 2 3 4 5
    The new array value is: 1 2 3 4 5
     
    四、从函数返回数组
    #!/bin/bash
    function arraydblr {
      #local 用来声明局部变量
      local origarray
      local newarray
      local elements
      local i
      origarray=($(echo "$@"))
      newarray=($(echo "$@"))
      elements=$[ $# - 1 ]
      for (( i = 0; i <= $elements; i++ ))
      {
        newarray[$i]=$[ ${origarray[$i]} * 2 ]
      }
      echo ${newarray[*]}
    }  
    myarray=(1 2 3 4 5)
    echo "The original array is: ${myarray[*]}"
    arg1=$(echo ${myarray[*]})
    result=($(arraydblr $arg1))
    echo "The new array is: ${result[*]}"
     
    五、递归函数
    function fact{
      if [ $1 -eq 1 ]
      then
        echo 1
      else:
        local temp=$[ $1 - 1 ]
        local result=$(factorial $temp)
        echo $[ $result * $1 ]
      fi
    }
    result=$(factorial $value)
     
    六、函数库文件
    使用函数库的关键在于source命令。source命令会在当前shell上下文中执行命令,而不是创建一个新shell。可以用source命令来在shell脚本中运行库文件脚本。这样脚本就可以使用库中的函数了。
    source命令有个快捷的别名,称作点操作符(dot operator)。要在shell脚本中运行myfuncs库文件,只需添加下面这行:
    . ./myfuncs
    Example:
    #!/bin/bash
    # using functions defined in a library file
    .  ./myfuncs
    value1=10
    value2=5
    result1=$(addem $value1 $value2)
    result2=$(multem $value1 $value2)
    echo "The result of adding them is: $result1"
    echo "The result of multiplying them is: $result2"
    也可以参考Home目录下的 .bashrc 文件
  • 相关阅读:
    jQuery 核心
    Visual Studio 文件没发布出来
    冷门JS技巧
    项目发布: error CS0103: 当前上下文中不存在名称“*****”
    jQuery编程的最佳实践
    HTML5中类jQuery选择器querySelector的使用
    html dl dt dd标签元素语法结构与使用
    EF Code First 更新数据库, 数据库迁移
    ASP.NET MVC中的拦截器
    C#Linq中的Union All/Union/Intersect和Top/Bottom和Paging和SqlMethods,skip,take,takewhile,skipwhile,编译查询等
  • 原文地址:https://www.cnblogs.com/z977690557/p/13962104.html
Copyright © 2011-2022 走看看