source命令

source [filename] 不再产生新的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. If filename does not contain a slash, file names in PATH are used to find the
directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix
mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt
builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the posi-
tional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return
status is the status of the last command exited within the script (0 if no commands are executed), and false if
filename is not found or cannot be read.

比如您在一个脚本里export $KKK=111 ,假如您用./a.sh执行该脚本,执行完毕后,您运行 echo $KKK
,发现没有值,假如您用source来执行 ,然后再echo
,就会发现KKK=111。因为调用./a.sh来执行shell是在一个子shell里运行的,所以执行后,结构并没有反应到父shell里,但是
source不同他就是在本shell中执行的,所以能够看到结果


举例:
lu1() {
echo 'aaaaaaaaa'
}

lu2() {
echo 'bbbbbbbbb'
}
上面就是,run.sh的源码了,可以看到只有2个函数定义没有任何地方来调用这两个函数,那么我们如果这样执行:
luther@gliethttp:~$ ./run.sh
luther@gliethttp:~$
可以看到什么都没有,因为没有地方调用这2个函数,我们希望在我们的luther@gliethttp:~$ 提示符后面调用这2个函数,来试试,
luther@gliethttp:~$ lu1
bash: lu1: command not found
luther@gliethttp:~$ lu2
bash: lu2: command not found
luther@gliethttp:~$
结果都提示找不到命令,是不是我们的这个需求shell还不提供支持呢,当然不是,这样有用的需求shell早就为我们做好解决方案了,来看看怎么实现,
shell中有2个命令可以完成我们的工作,一个是source另一个就是和source等效的.逗号运算符:
luther@gliethttp:~$ . run.sh或者luther@gliethttp:~$source run.sh
这样我们run.sh脚本中创建的变量和函数就添加到了执行.或source的shell,直到关闭该shell窗口,否则run.sh中创建的变量和函数将一直有效,
如果我们只是执行./run.sh启动一个subshell来运行我们的run.sh脚本,那么run.sh脚本中的变量和函数将紧紧影响到由shell启动的subshell,当./run.sh脚本退出之后,run.sh变量和函数的影响寿命也到了尽头。
来看看现在的现象:
luther@gliethttp:~$ ./run.sh
luther@gliethttp:~$ lu1
bash: lu1: command not found
luther@gliethttp:~$ lu2
bash: lu2: command not found
luther@gliethttp:~$ . run.sh
luther@gliethttp:~$ lu1
aaaaaaaaa
luther@gliethttp:~$ lu2
bbbbbbbbb
luther@gliethttp:~$
重新启动一个新shell:
luther@gliethttp:~$ ./run.sh
luther@gliethttp:~$ lu1
bash: lu1: command not found
luther@gliethttp:~$ lu2
bash: lu2: command not found
luther@gliethttp:~$ source run.sh
luther@gliethttp:~$ lu1
aaaaaaaaa
luther@gliethttp:~$ lu2
bbbbbbbbb
luther@gliethttp:~$

1、执行脚本时是在一个子shell环境运行的,脚本执行完后该子shell自动退出。2、一个shell中的系统环境变量才会被复制到 子shell中(用export定义的变量);3、一个shell中的系统环境变量只对该shell或者它的子shell有效,该shell结束时变量消 失(并不能返回到父shell中)。3、不用export定义的变量只对该shell有效,对子shell也是无效的。
不管怎么设置,不会多层继承,对子子shell是没任何用的。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值