利用source命令将子shell srcipt进程中的变量提升到父shell进程中来
来源:互联网 发布:韩国研究生留学知乎 编辑:程序博客网 时间:2024/06/08 11:32
我们先来看一个操作, 为了便于说明, 我就直接在命令后面进行注释, 并以#开头
[taoge@localhost Desktop]$ echo $$ # 查阅当前shell进程的进程号码2455[taoge@localhost Desktop]$ cat a.sh # 查阅a.sh中的内容#! /bin/bashecho "shell script"x="good x"[taoge@localhost Desktop]$ ./a.sh # 执行./a.shshell script[taoge@localhost Desktop]$ echo $x # 看一下x的值, 结果发现x没有值, 为什么呢? 因为子的变量没有到父中[taoge@localhost Desktop]$ source ./a.sh # 用source执行一下./a.sh, 意味着把子的变量导入到父中shell script[taoge@localhost Desktop]$ echo $x # 在父中查看一下x, 果然有值了good x[taoge@localhost Desktop]$ bash # 进入子bash shell[taoge@localhost Desktop]$ echo $$ 2592[taoge@localhost Desktop]$ echo $x # 看一下子bash shell中的x, 发现没有, 因为父shell中的x不是“临时环境变量”, 而是普通变量, 在子bash shell中不生效[taoge@localhost Desktop]$ exit # 退出到父shell中exit[taoge@localhost Desktop]$ export x # 将父shell中的普通变量x变为“临时环境变量”x[taoge@localhost Desktop]$ bash # 再次进入子bash shell[taoge@localhost Desktop]$ echo $$2613[taoge@localhost Desktop]$ echo $x # 查阅x, 发现有值了good x[taoge@localhost Desktop]$ exitexit[taoge@localhost Desktop]$ echo $$ # 再次退出到父shell中2455[taoge@localhost Desktop]$
从上面的操作和结果, 我们可以看到: 单纯执行shell脚本./a.sh, 并不能把脚本中定义的变量导入到父shell中, 必须用source的方式执行才可以。
还有一个问题, 从上面我们可以看到, source ./a.sh后, x在父shell中仍然是普通变量, 需要export变为“临时环境变量”, 多了一步人为操作, 多不爽啊。 其实, 我们完全可以在a.sh中先用export, 如下:
[taoge@localhost Desktop]$ echo $$2455[taoge@localhost Desktop]$ cat a.sh #! /bin/bashecho "shell script"export y="good y"[taoge@localhost Desktop]$ ./a.sh shell script[taoge@localhost Desktop]$ echo $y[taoge@localhost Desktop]$ source ./a.sh shell script[taoge@localhost Desktop]$ echo $ygood y[taoge@localhost Desktop]$ bash[taoge@localhost Desktop]$ echo $$2792[taoge@localhost Desktop]$ echo $y # 有值了!!!good y[taoge@localhost Desktop]$ exitexit[taoge@localhost Desktop]$ echo $$2455[taoge@localhost Desktop]$
可以看到, 实现了我们预期的结果。
最后总结一下:单纯执行shell脚本./a.sh, 并不能把脚本中定义的变量(普通变量或“临时环境变量”)导入到父shell中, 必须用source的方式执行才可以把变量(普通变量或“临时环境变量”)导入到父shell中。 这么看起来, export和source颇有点“相反"的感觉。
在实际的linux软件开发过程中, export和source到处可见。
0 0
- 利用source命令将子shell srcipt进程中的变量提升到父shell进程中来
- shell 中export变量导出到子进程
- Shell脚本中的return,exit 0,以及 父进程获取子进程的变量
- shell子进程解析
- shell子进程
- [精华] [shell问答录]:命令、进程、子shell...
- 在shell 中利用命令查看某个进程的进程id
- shell中source命令
- shell中的多进程
- linux中的shell 进程
- shell脚本 杀进程及其子进程
- [shell] kill 进程及子进程
- linux中根据端口号来关闭进程的shell命令
- 除了在DDMS中可以查看进程,我们还可以通过shell命令来查看
- linux shell 中source 命令
- adb shell进程管理命令
- Shell命令——进程
- linux shell 进程查看命令
- 【数据结构-队列】链式队列
- 这时我们需要ResourceBundle。http://blog.csdn.net/jdenght/article/details/908658
- 你的生存模式正确吗?
- 物联网落地的支撑力量–物联网运营平台
- 欢迎使用CSDN-markdown编辑器
- 利用source命令将子shell srcipt进程中的变量提升到父shell进程中来
- 面向对象之接口的理解
- 黑马程序员-----面向对象
- 修改phpmyadmin中的默认超时时间
- 作业5.18
- Tcl中upvar的用法
- 二分查找法用—for循环— 实现
- Viewpager中嵌套Listview,而且Listview的item中夹杂ViewPager
- 链表算法-链表前面插入节点