export的简单应用

1438阅读 0评论2011-08-10 随1意2o
分类:Python/Ruby

如果要传递函数给子shell环境使用,可使用export和-f选项
用法:
export -f 函数名

实际例子如下:
function3.sh  如下:
 1 #! /bin/bash                                                                                                                     
  2
  3 #把$2的内容转向附加到$1指定的文件中
  4 #Auter:panda
  5 #Time:2011-08-10
  6 appendfile() {
  7     echo "$2" >> "$1"
  8 }
  9
 10 Dir=~/tmp
 11 OutFile="$Dir/tmp.txt"
 12
 13 #如果目录不存在则会创建新的目录
 14 [ -e $Dir ] || mkdir -p $Dir
 15
 16 appendfile $OutFile "函数可以这样用"
 17 appendfile $OutFile "这是函数的另一种用法"
 18 appendfile $OutFile "Over. "
 19
 20 appendfile $OutFile "函数可以这样用"
 21 export -f appendfile
 22
 23 ./test_path.sh

  test_path.sh如下:        1#!/bin/bash                                                                                                                      
  2
  3 appendfile ~/tmp/tmp.txt "wangpanda"

执行结果如下
panda@panda-pc:~/Code/Shell$ ./function3.sh
panda@panda-pc:~/Code/Shell$ cd ~/tmp
panda@panda-pc:~/tmp$ cat tmp.txt
函数可以这样用
这是函数的另一种用法
Over.
函数可以这样用
wangpanda
panda@panda-pc:~/tmp$

注:子shell向文件写入的是wangpanda

上一篇:exit和return
下一篇:建立函数库 简单实际应用