The difference experiment of several different execution methods of shell script

Shell scripts can be executed in three ways. According to whether to create a subshell during execution, it can be divided into two categories. My test script and test results are posted below.

#! /bin/bash
cd 
echo "this shell's pid is $$"  #打印执行脚本进程的pid

#执行shell脚本方式可以分为两类:
#a. 创建一个子shell, 即一个新的进程,然后在里面执行脚本。
#   ./shell.sh
#   shell-absolute-path/shell.sh #这两种方式,要求执行用户有执行权限。
#   bash shell.sh
#   sh  shell.sh    #这两种方式可以在用户对shell.sh没有执行权限时执行。
#b. 不创建子shell,直接在当前shell中执行脚本:
#   . shell.sh    #前面是点号。
#   source shell.sh #这两种方式,是否让你想起了什么,对,当我们修改了.bashrc,要让他马上生效时,采用的就是这种执行方式。
#  分别用以上方式执行该脚本,你会发现区别的

Experimental results:



It can be seen that using. And source to execute the pid of the script shell is the same as the pid of the current environment shell, no subshell will be created, and the cd command in the script can change the context of the current shell as it is executed in the current shell.

Except for other execution methods, there is no such feature. The pid of shel is different from the current shell when they are executed, so the effect of the cd command is not seen because it only changes the context of the subshell that executes it. The environment has no effect on the current shell.

Guess you like

Origin blog.csdn.net/lx1848/article/details/52099728