Chinaunix首页 | 论坛 | 博客
  • 博客访问: 465164
  • 博文数量: 93
  • 博客积分: 5006
  • 博客等级: 上校
  • 技术积分: 1002
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-30 13:58
文章分类

全部博文(93)

文章存档

2012年(2)

2011年(68)

2010年(23)

分类: Python/Ruby

2011-08-10 20:46:51

如果要传递函数给子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

阅读(1358) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~