【总结】关于shell执行,export 和 source

1、执行脚本时是在一个子shell环境运行的,脚本执行完后该子shell自动退出

[acefei@localhost  : ~/shell] ^_^
$cat 1.sh
#!/bin/bash
echo "In 1.sh : Invoking 2.sh"
./2.sh
echo "In 1.sh : now path is `pwd`"
echo "In 1.sh : exit"


[acefei@localhost  : ~/shell] ^_^
$cat 2.sh
#!/bin/bash
cd /tmp
echo "In 2.sh : now path is `pwd`"
echo "In 2.sh : exit"

[acefei@localhost  : ~/shell] ^_^
$./1.sh
In 1.sh : Invoking 2.sh
In 2.sh : now path is /tmp
In 2.sh : exit
In 1.sh : now path is /home/acefei/shell
In 1.sh : exit

2、一个shell中的系统环境变量才会被复制到子shell中(用export定义的变量)

[acefei@localhost  : ~/shell] ^_^
$cat 1.sh
#!/bin/bash
echo "In 1.sh : export a = 123"
export a=123
echo "In 1.sh : Invoking 2.sh"
./2.sh
echo "In 1.sh : exit"


[acefei@localhost  : ~/shell] ^_^
$cat 2.sh
#!/bin/bash
echo "In 2.sh : a = $a"
echo "In 2.sh : exit"

[acefei@localhost  : ~/shell] ^_^
$./1.sh
In 1.sh : export a = 123
In 1.sh : Invoking 2.sh
In 2.sh : a = 123
In 2.sh : exit
In 1.sh : exit

3、一个shell中的系统环境变量只对该shell或者它的子shell有效,该shell结束时变量消失(并不能返回到父shell中)

[acefei@localhost  : ~/shell] ^_^
$cat 2.sh
#!/bin/bash
echo "In 2.sh : Invoking 1.sh"
./1.sh
echo "In 2.sh : a = $a"
echo "In 2.sh : exit"

[acefei@localhost  : ~/shell] ^_^
$cat 1.sh
#!/bin/bash
echo "In 1.sh : export a = 123"
export a=123
echo "In 1.sh : exit"


[acefei@localhost  : ~/shell] ^_^
$./2.sh
In 2.sh : Invoking 1.sh
In 1.sh : export a = 123
In 1.sh : exit
In 2.sh : a =
In 2.sh : exit

4、不用export定义的变量只对该shell有效,对子shell也是无效的


Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

直接执行一个脚本文件是在一个子shell中运行的,而source则是在当前shell环境中运行的。

[acefei@localhost  : ~/shell] ^_^
$cat 1.sh
#!/bin/bash
echo "In 1.sh : define a = 123"
a=123
echo "In 1.sh : exit"


[acefei@localhost  : ~/shell] ^_^
$cat 2.sh
#!/bin/bash
echo "In 2.sh : source 1.sh"
#./1.sh
source ./1.sh
echo "In 2.sh : a = $a"
echo "In 2.sh : exit"

[acefei@localhost  : ~/shell] ^_^
$./2.sh
In 2.sh : source 1.sh
In 1.sh : define a = 123
In 1.sh : exit
In 2.sh : a = 123
In 2.sh : exit



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值