首页 > 系统服务 > 详细

Shell之Function与Source

时间:2019-10-01 09:14:08      阅读:90      评论:0      收藏:0      [点我收藏+]

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

技术分享图片

函数传参

实例:

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}"

技术分享图片

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的结果:

技术分享图片

Shell之Function与Source

原文:https://www.cnblogs.com/zakzhu/p/11614694.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!