当您调用source(或其别名.)时,您将脚本插入当前的bash进程中.所以你可以读取脚本设置的变量.
当你调用sh时,你启动一个fork(子进程)来运行/ bin / sh的新会话,这通常是bash的符号链接.在这种情况下,子脚本完成后,将删除子脚本设置的环境变量.
注意:sh可能是另一个shell的符号链接.
一个小样本
例如,如果要以特定方式更改当前工作目录,则无法执行此操作
cat <myCd2Doc.sh
#!/bin/sh
cd /usr/share/doc
eof
chmod +x myCd2Doc.sh
这不符合您的期望:
cd /tmp
pwd
/tmp
~/myCd2Doc.sh
pwd
/tmp
因为当前工作目录是环境的一部分,myCd2Doc.sh将在子shell中运行.
但:
cat >myCd2Doc.source <
# Shell source file
myCd2Doc() {
cd /usr/share/doc
}
eof
. myCd2Doc.source
cd /tmp
pwd
/tmp
myCd2Doc
pwd
/usr/share/doc
(我写了一个mycd函数的小样本.)
执行级别$SHLVL
cd /tmp
printf %b '\43\41/bin/bash\necho This is level \44SHLVL.\n' >qlvl.sh
bash qlvl.sh
This is level 2.
source qlvl.sh
This is level 1.
cat <qlvl.sh
#!/bin/bash
export startLevel
echo This is level $SHLVL starded:${startLevel:=$SHLVL}.
((SHLVL<5)) && ./qlvl.sh
eoqlvl
chmod +x qlvl.sh
./qlvl.sh
This is level 2 starded:2.
This is level 3 starded:2.
This is level 4 starded:2.
This is level 5 starded:2.
source qlvl.sh
This is level 1 starded:1.
This is level 2 starded:1.
This is level 3 starded:1.
This is level 4 starded:1.
This is level 5 starded:1.
最后的测试:
printf %b '\43\41/bin/bash\necho Ending this.\nexit 0\n' >finalTest.sh
bash finalTest.sh
Ending this.
source finalTest.sh
Ending this.
…您可能会注意到两种语法之间存在不同的行为. ?