【总结】关于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



你可能感兴趣的:(shell,脚本,command,Path)