微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 使用`sh`和`source`有什么区别?

sh和source之间有什么区别?

source: source filename [arguments]
    Read and execute commands from FILENAME and return.  The pathnames
    in $PATH are used to find the directory containing FILENAME.  If any
    ARGUMENTS are supplied, they become the positional parameters when
    FILENAME is executed.

对于男人来说:

NAME
       bash - GNU Bourne-Again SHell

SYnopSIS
       bash [options] [file]

copYRIGHT
       Bash is copyright (C) 1989-2004 by the Free Software Foundation, Inc.

DESCRIPTION
       Bash  is  an sh-compatible command language interpreter that executes commands read from the standard input or from a file.  Bash also incorporates
       useful features from the Korn and C shells (ksh and csh).

       Bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools specification (IEEE Working Group 1003.2).

解决方法:

当您调用source(或其别名.)时,您将脚本插入当前的bash进程中.所以你可以读取脚本设置的变量.

当你调用sh时,你启动一个fork(子进程)来运行/ bin / sh的新会话,这通常是bash的符号链接.在这种情况下,子脚本完成后,将删除子脚本设置的环境变量.

注意:sh可能是另一个shell的符号链接.

一个小样本

例如,如果要以特定方式更改当前工作目录,则无法执行此操作

cat <<eof >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 <<eof
# 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.

recursion

cat <<eoqlvl >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.

…您可能会注意到两种语法之间存在不同的行为.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐