shell子进程修改父进程的环境变量值

转自:http://blog.chinaunix.net/uid-22666248-id-275553.html

脚本中的环境变量通过 export 导出,可以使这脚本调用其他脚本使用这个变量

这里有两个脚本程序 hello  和 hello1
 

  1. hello 脚本代码
  2.  
  3. #!/bin/bash
  4.  
  5. FILM="Front of the class"
  6. #export FILM   这里我注释掉 export 命令
  7. echo $FILM
  8. ./hello1          ##调用./hello1脚本,打印FILM,注意这里是 父与子 进程的调用关系
  1. hello1 脚本程序
  2.  
  3. #!/bin/bash
  4. echo $FILM in hello1    打印FILM变量


果我们注释掉export 输出变量,那么在 hello1 只是打印出 in hello1 ,引文FILM 是空

打印输出
 

  1. ywx@yuweixian:~/yu/course/hello$ ./hello
  2. Front of the class
  3. in hello1


如果我们加上 export $FILM 的话,我们就可以打印出 Front of the class
 

  1. ywx@yuweixian:~/yu/course/hello$ ./hello
  2. Front of the class
  3. Front of the class in hello1


注意一点:./hello1 父子进程调用关系,hello1 是在 hello 

开辟的子进程中运行



*****************************************************************

如果我们在 子进程中修改 FILM 的值,会不会在 父进程中改变呢??


不会,首先,通过./hello1 方式调用,是父子进程的关系,export 是单向传递,从父

进程到子进程,不能从子进程到父进程。当子进程撤消后,变

量值也就消失了,不会改变变量值




请看:还是hello 和 hello1 两个脚本程序
 

  1. hello 程序
  2. #!/bin/bash
  3.  
  4. FILM="Front of the class"
  5. export FILM                      ##导出 变量
  6. echo $FILM before hello          ## hello 第一次打印 变量
  7. ./hello1                         ## 调用hello1 脚本程序
  8. echo $FILM after hello           ## 打印 在 hello1 修改变量后的值
  1. #!/bin/bash
  2. echo $FILM in hello1 first           ##第一次打印 父进程 中变量值
  3. FILM="MODIFY"                        ## 修改  变量值
  4. echo $FILM in hello1 second          ## 打印修改过的值

结果我们可以看到,

    在 子进程 hello1 中,会正确打印出 修改过的值,但是在

父进程中还是打印原先的值





*********************************************************************************
如果我们想  打印子进程中修改过的变量值,我们应该怎么办

呢??


这里我们使用 "." 点命令 详细请看 点命令赏析

我们就要改变 父子进程关系,我们修改为同等进程使用 . ./hello1 这个方式调用

这种方式就可以使得 hello 和 hello1 在同一个进程中了,变量可以传值了

在 hello 中修改为

  1. #!/bin/bash
  2.  
  3. FILM="Front of the class"
  4. export FILM
  5. echo $FILM before hello
  6. . ./hello1
  7. echo $FILM after hello
  1. ywx@yuweixian:~/yu/course/hello$ ./hello
  2. Front of the class before hello
  3. Front of the class in hello1 first
  4. MODIFY in hello1 second
  5. MODIFY after hello
  6. ywx@yuweixian:~/yu/

猜你喜欢

转载自blog.csdn.net/xymyeah/article/details/88249387