shell如何模块化和复用——shell深入学习

shell如何模块化和复用——shell深入学习
2011-09-18 星期天 阴天

基本上所有的编程语言都支持模块化,以达到功能复用的效果。比如java和python的import xxx。C/C++的include。那么shell支持模块化吗?

shell本质上并不支持模块化,但是有些机制可以使它达到类似的效果。

首先要了解有两种方式可以执行一个shell脚本:
1. 一种是新产生一个shell,然后执行相应的shell scripts:
方法是在scripts文件开头加入以下语句
#!/bin/bash
一般的script文件(.sh)即是这种用法。这种方法先启用新的sub-shell(新的子进程),然后在其下执行命令。
也可以指定shell类型,如:
$sh script文件
2. 一种是在当前shell下执行,不再启用其他shell:
方法是使用source命令,不再产生新的shell,而在当前shell下执行一切命令。
也有两种语法:
$source script文件
或者直接用点号:. script文件(sh 只支持点号,不支持source命令,所以建议使用点号)

一个非常形象的类比是:shell的source就是C中的include。

注意:shell不会判断一个shell脚本是不是被导入多次,每次source(或者点号)scriptFile,都会在当前shell中执行scriptFile。这点和C的include是一样的。正如C可以使用条件包含避免重复导入头文件,shell也有类似的机制。这个我们在下面会讲到。

了解了背后的原理和机制,现在让我们回过头来看看client shell中如何导入module shell。
一个例子胜过千言万语,我们将采用循序渐进的方式逐渐修复到最完美的方案。

先解决最简单的导入情况——module shell和client shell在一个文件夹下:
子模块定义:
forrest@forrest-laptop:~/study/shell$ cat amodule.sh 
#!/bin/bash

global_var="This is a global variable define in amodule."

say_hello(){
        global_var_define_in_function="This is a global variable define in a function in amodule." 
        local local_var="This is a local variable define in a function in amodule." 
        echo "Hello, $1. This is a function define in amodule."        
}

使用脚本定义:
forrest@forrest-laptop:~/study/shell$ cat main.sh 
#!/bin/bash

. ./amodule.sh

say_hello "Forrest Gump"
echo "global_var=$global_var"
echo "global_var_define_in_function=$global_var_define_in_function"
echo "local_var=$local_var"

执行结果:
forrest@forrest-laptop:~/study/shell$ ./main.sh 
Hello, Forrest Gump. This is a function define in amodule.
global_var=This is a global variable define in amodule.
global_var_define_in_function=This is a global variable define in a function in amodule.
local_var=

可以看到,在main.sh中通过source amodule.sh,main.sh可以直接使用amodule.sh中定义的全局变量和函数。而局部变量是拿不到的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值