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.
[Plain]View plaincopy
- 1. Sh
- #! /Bin/bash
- A = B
- Echo "PID for 1.sh before exec/source/fork: $"
- Export
- Echo "1.sh:\ $ A is $"
- Case $1 in
- Exec)
- Echo "using exec ..."
- Exec./2.sh ;;
- Source)
- Echo "using source ..."
- ../2.sh ;;
- *)
- Echo "using fork by default ..."
- ./2.sh ;;
- Esac
- Echo "PID for 1.sh after exec/source/fork: $"
- Echo "1.sh:\ $ A is $"
[Plain]View plaincopy
- 2. Sh
- Code:
- #! /Bin/bash
- Echo "PID for 2.sh: $"
- Echo "2.sh get \ $ A = $ A from 1.sh"
- A = C
- Export
- Echo "2.sh:\ $ A is $"
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
[Plain]View plaincopy
- Echo "PID for 1.sh after exec/source/fork: $"
- Echo "1.sh:\ $ A is $"
These two commands are not executed
In this example, we can understand the differences between them.
Exec, source, and bash differences (zz)