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

来源:互联网 发布:淘宝网络兼职 编辑:程序博客网 时间:2024/06/08 07:15

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

[acefei@localhost  : ~/shell] ^_^$cat 1.sh#!/bin/bashecho "In 1.sh : Invoking 2.sh"./2.shecho "In 1.sh : now path is `pwd`"echo "In 1.sh : exit"[acefei@localhost  : ~/shell] ^_^$cat 2.sh#!/bin/bashcd /tmpecho "In 2.sh : now path is `pwd`"echo "In 2.sh : exit"[acefei@localhost  : ~/shell] ^_^$./1.shIn 1.sh : Invoking 2.shIn 2.sh : now path is /tmpIn 2.sh : exitIn 1.sh : now path is /home/acefei/shellIn 1.sh : exit

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

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

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

[acefei@localhost  : ~/shell] ^_^$cat 2.sh#!/bin/bashecho "In 2.sh : Invoking 1.sh"./1.shecho "In 2.sh : a = $a"echo "In 2.sh : exit"[acefei@localhost  : ~/shell] ^_^$cat 1.sh#!/bin/bashecho "In 1.sh : export a = 123"export a=123echo "In 1.sh : exit"[acefei@localhost  : ~/shell] ^_^$./2.shIn 2.sh : Invoking 1.shIn 1.sh : export a = 123In 1.sh : exitIn 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/bashecho "In 1.sh : define a = 123"a=123echo "In 1.sh : exit"[acefei@localhost  : ~/shell] ^_^$cat 2.sh#!/bin/bashecho "In 2.sh : source 1.sh"#./1.shsource ./1.shecho "In 2.sh : a = $a"echo "In 2.sh : exit"[acefei@localhost  : ~/shell] ^_^$./2.shIn 2.sh : source 1.shIn 1.sh : define a = 123In 1.sh : exitIn 2.sh : a = 123In 2.sh : exit



原创粉丝点击