In bash shell, source, exec, and sh can be used to execute shell scripts, but what are their differences?
SH: the parent process fork a sub-process, and shell script is executed in the sub-process.
Source: executed in the original process, not Fork sub-process
Exec: execute in the original process, but terminate the original process at the same time
Note: using export will inherit the variables in the parent process from the child process, but in turn it will not work. In the child process, no matter if the environment changes, it will not affect the parent process.
The following is an example.
1.sh#!/bin/bashA=Becho "PID for 1.sh before exec/source/fork:$"export Aecho "1.sh: \$A is $A"case $1 in exec) echo "using exec..." exec ./2.sh ;; source) echo "using source..." . ./2.sh ;; *) echo "using fork by default..." ./2.sh ;;esacecho "PID for 1.sh after exec/source/fork:$"echo "1.sh: \$A is $A"
2.shCODE:#!/bin/bashecho "PID for 2.sh: $"echo "2.sh get \$A=$A from 1.sh"A=Cexport Aecho "2.sh: \$A is $A"
Run the following command in the command line:
./1.sh fork
As you can see, 1. SH is executed in the parent process, 2. SH is executed in the child process. The PID of the parent process is 5344, while that of the child process is 5345. After the child process is executed, the control is returned to the parent process. At the same time, changing the value of environment variable a in a sub-process does not affect the parent process.
./1.sh Source
The results show that 1. SH and 2. Sh are executed in the same process, and the PID is 5367.
./1.sh Exec
We can see that both scripts are executed in the same process, but note that the original parent process is terminated using exec. Therefore, we can see that
echo "PID for 1.sh after exec/source/fork:$"echo "1.sh: \$A is $A"
These two commands are not executed
In this example, we can understand the differences between them.