创建函数

#创建函数的意义在于避免代码的重复编写
#函数的创建以及使用

基本的脚本函数
    创建函数的2种格式:
        ①
        function  name {  
        commands
        }
        ②
        name () {
        commands
        }
    函数的使用
        $
        function func1 {
            echo "This is an example of a function"
        }
        count=1
        while [ $count -le 5 ]
        do
            func1
            count=$[ $count + 1 ]
        done
        function func1 {                    -- 同名函数func1的定义将覆盖之前的函数
            echo "This is an same function"
        }        
        echo "This is the end of the loop"
        func1
        echo "Now this is the end of the script $?"    -- $? 改变量可以查看函数退出状态码,为0表示函数最后一行代码执行成功
        $
    返回值
        避免使用函数的默认状态码(return)
            $
            function dbl {
                read -p "Enter a value: " value
                echo "doubling the value"
                return $[ $value * 2 ]
            }
            dbl
            echo "The new value is $?"  -- 注意2点:函数一结束就取返回值;退出状态码必须是0~255。
            $
        使用函数输出
            $
            function dbl {
                read -p "Enter a value: " value
                echo $[ $value * 2 ]
            }
            result=$(dbl)  -- 该脚本会获取 dbl 函数的输出,而不是查看退出状态码
            echo "The new value is $result"
            $
    在函数中使用变量            
        传递参数
            #sh sw_cs.sh 10 15
            $
            function func7 {     
                echo $[ $1 * $2 ]
            }
            if [ $# -eq 2 ]
            then
                value=$(func7 $1 $2)  -- 向函数传递变量(函数符合位置变量标准,如func7 10 23,但函数不能直接使用脚本的变量)
                echo "The result is $value"
                else
                echo "Usage: badtest1 a b"
            fi
            $
        脚本全局变量与脚本局部变量
            $
            function func1 {
                local temp=$[ $value + 5 ]  -- local定义了该变量作为脚本局部变量,不会覆盖脚本全局变量的值。作用域只在改函数。
                result=$[ $temp * 2 ]
            }
            temp=4
            value=6
            func1
            echo "The result is $result"
            if [ $temp -gt $value ]
            then
                echo "temp is larger"  -- The result is 22
            else
                echo "temp is smaller"  -- temp is smaller 
            fi
            $
    数组变量参数的处理
        传递数组参数
            $
            function testit {
                local newarray
                newarray=(;'echo "$@"')    -- 将数组参数变量打印,否则只会读取第一个
                echo "The new array value is: ${newarray[*]}"
            }
            myarray=(1 2 3 4 5) 
            echo "The original array is ${myarray[*]}"  -- The original array is 1 2 3 4 5
            testit ${myarray[*]}  -- The new array value is: 1 2 3 4 5
            $
            function addarray {
                local sum=0
                local newarray
                newarray=($(echo "$@"))
                for value in ${newarray[*]}
                do
                    sum=$[ $sum + $value ]
                done
                echo $sum
            }
            myarray=(1 2 3 4 5)
            echo "The original array is: ${myarray[*]}"
            arg1=$(echo ${myarray[*]})
            result=$(addarray $arg1)
            echo "The result is $result"    -- The result is 15,addarray 函数会遍历所有的数组元素,将它们累加在一起
            $
        返回数组
            function arraydblr {
                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 ]    -- 将数组origarray[$i]的该位置参数作为变量的值
                }
                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[*]}"    -- The new array is: 2 4 6 8 10
    函数递归
        $
        function factorial {
            if [ $1 -eq 1 ]
            then
                echo 1
            else
                local temp=$[ $1 - 1 ]
                local result=$(factorial $temp)
                echo $[ $result * $1 ]
            fi
        }
        read -p "Enter value: " value
        result=$(factorial $value)
        echo "The factorial of $value is: $result"
        $        
脚本中使用其他脚本函数(source)
    创建库(实现脚本中调用其他脚本中函数)
        $
        function addem {
            echo $[ $1 + $2 ]
        }
        function multem {
            echo $[ $1 * $2 ]
        }
        function divem {
            if [ $2 -ne 0 ]
            then
                echo $[ $1 / $2 ]
            else
                echo -1
            fi
        }
        $
        $
        source myfuncs.sh  -- 用 source 命令来在shell脚本中运行库文件脚本,相当于将两个脚本合并成一个
        value1=10
        value2=5
        result1=$(addem $value1 $value2)
        result2=$(multem $value1 $value2)
        result3=$(divem $value1 $value2)
        echo "The result of adding them is: $result1"  -- 15
        echo "The result of multiplying them is: $result2"  -- 50
        echo "The result of dividing them is: $result3"  -- 2
        $
命令行上使用函数
    命令行上直接创建函数(临时创建)
        $ function divem { echo $[ $1 / $2 ]; }  -- 每条命令结束需要分号
        $ divem 100 5
        $
        $ function multem {
        > echo $[ $1 * $2 ]  -- 多行创建不需要分号
        > }
        $ multem 2 5
    在.bashrc 文件中定义函数(永久创建,重启了shell可用。使用是不需要定义,可以直接使用函数)
        1. 直接定义函数
            $ cat .bashrc
            # .bashrc
            # Source global definitions
            if [ -r /etc/bashrc ]; then
            . /etc/bashrc
            fi
            function addem {   -- 该addem函数是追加的函数
            echo $[ $1 + $2 ]
            }
            $
        2. 读取函数文件
            $ cat .bashrc
            # .bashrc
            # Source global definitions
            if [ -r /etc/bashrc ]; then
            . /etc/bashrc
            fi
            . /home/rich/libraries/myfuncs  -- 该脚本文件myfuncs为追加的,使用了source命令以便和其他脚本合并。
            $
实例
    下载及安装GNU shtool库
        地址:ftp://ftp.gnu.org/gnu/shtool/shtool-2.0.8.tar.gz
        复制到主目录中(cp)
        使用tar提取:tar -zxvf shtool-2.0.8.tar.gz
    构建库
        $ ./confifgure    -- configure 命令会检查构建shtool库文件所必需的软件
        $ make    -- make 命令负责构建shtool库文件
        $ make test    -- 测试模式会测试shtool库中所有的函数是否通过
        $ make install    -- 安装到linux的公共环境(若测试都通过)
    shtool 库函数
        函 数         描 述
        Arx         创建归档文件(包含一些扩展功能)
        Echo        显示字符串,并提供了一些扩展构件
        fixperm     改变目录树中的文件权限
        install     安装脚本或文件
        mdate       显示文件或目录的修改时间
        mkdir       创建一个或更多目录
        Mkln        使用相对路径创建链接
        mkshadow    创建一棵阴影树
        move        带有替换功能的文件移动
        Path        处理程序路径
        platform    显示平台标识
        Prop        显示一个带有动画效果的进度条
        rotate      转置日志文件
        Scpp        共享的C预处理器
        Slo         根据库的类别,分离链接器选项
        Subst       使用sed的替换操作
        Table       以表格的形式显示由字段分隔(field-separated)的数据
        tarball     从文件和目录中创建tar文件
        version     创建版本信息文件
        shtool库函数的使用格式:
            shtool [options] [function [options] [args]]
    使用shtool库
        $ ls –al /usr/bin | shtool prop –p "waiting..."  -- 使用shtool的prop函数
        waiting...
        $
生活就要逢山开路遇水搭桥,愿共勉!
原文地址:https://www.cnblogs.com/TianMu/p/11199389.html