Shell之Function与Source

Shell之Function与Source

😄 Written by Zak Zhu

学习python风格, 优雅规范书写shell代码

参考

Fuction的编写

函数语法

定义格式:

[function] foo() {
    COMMANDS
    [return N]		# 返回码(N)的取值范围: 0~255
}

调用格式:

foo	[ARGS]

实例:

# Defined function
function hello() {
    echo "Hello World !"
}

# Invoke function
hello

1

函数传参

实例:

function two_num_sum() {
    let sum=$1+$2
    return ${sum}
}

read -p "Please input the first number: " arg1
read -p "Please input the second number: " arg2
two_num_sum ${arg1} ${arg2}
ret=$?
echo "The sum of two numbers is ${ret}"

2

Source的使用

和其他语言一样, Shell也可以包含外部脚本. 这样可以很方便的封装一些公用的代码作为一个独立的文件.

实例:

  • functions.sh文件:

    function hello() {
        echo "Hello World !"
    }
    
    function two_num_sum() {
        let sum=$1+$2
        return ${sum}
    }
    
  • bin.sh文件:

    #!/bin/bash
    
    #####################################
    # @Author: 
    # @Created Time: 2019-10-01 02:07:32
    # @Description: 
    #####################################
    
    
    source ./functions.sh
    
    hello
    
    read -p "Please input the first number: " arg1
    read -p "Please input the second number: " arg2
    two_num_sum ${arg1} ${arg2}
    ret=$?
    echo "The sum of two numbers is ${ret}"
    
    

执行bin.sh的结果:

3

posted @ 2019-10-01 02:16  ZakZhu  阅读(657)  评论(0编辑  收藏  举报