shell如何模块化和复用——shell深入学习
2011-09-18 星期天 阴天
基本上所有的编程语言都支持模块化,以达到功能复用的效果。比如java和python的import xxx。C/C++的include。那么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也有类似的机制。这个我们在下面会讲到。
一个例子胜过千言万语,我们将采用循序渐进的方式逐渐修复到最完美的方案。
先解决最简单的导入情况——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中定义的全局变量和函数。而局部变量是拿不到的。