export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed. The -n option causes the export property to be removed from each name.
If a variable name is followed by =word, the value of the variable is set to word. export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.
例子:父脚本使用export命令导出变量和函数,是之能在其调用的子脚本中访问。注意被导出的变量不同于传统意义上的全局变量,因为子脚本只是获得了一份父脚本导出变量的拷贝。
父脚本source.sh:
AA=11
export AA
BB=22
export -n BB #export -p
my_func() {
echo AA = $AA
echo BB = $BB
return }
export -f my_func
if [ -f sub_shell.sh ]
then
echo
echo call sub shell!
echo
./sub_shell.sh
fi echo source.sh\'s AA BB: my_func |
子脚本sub_shell.sh
echo sub_shell now!
my_func
AA=33
|
运行结果:
call sub shell!
sub_shell now! AA = 11 BB =
source.sh's AA BB: AA = 11 BB = 22
|
由上面的例子可以看到,父脚本使用export命令导出了变量AA,BB 函数my_func. 然后在子脚本中访问,可以看到export -n导出的变量在子脚本得到的对应拷贝中会被置为空值, 导出函数需要使用export -f. 由于子脚本访问的是父脚本导出变量的拷贝,所以对于他们的修改,对于父脚本不可见。
阅读(1107) | 评论(0) | 转发(0) |