Fork, source and exec differences in running scripts
When the fork method is used to run the script, the shell (parent process) generates a child process to execute the script. When the child process ends, the parent process is returned, however, the environment of the parent process will not change because of the change of the child process. when the source method is used to run a script, the script is executed in the current process, rather than a child process. because all execution results are completed in the current process, if the script environment changes, the current process environment will also change. when exec is used to run a script in exec mode, it is the same as source, so that the script is executed in the current process, The remaining part of the original code will be terminated. Similarly, the environment in the process changes with the script. Conclusion: Generally, If we execute the code, the fork is used by default. You can run the pstree command to check the relationship between parent and child processes. As shown above, if you want the parent process to get the environment variable of the child process, it is the script [SQL] # in source Mode 1. sh! /Bin/bash A = B echo "PID for 1.sh before exec/source/fork: $" export A echo "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; esac echo "PID for 1.sh after exec/source/fork: $" echo "1.sh:\ $ A is $ A" 2. sh script [SQL] #! /Bin/bash echo "PID for 2.sh:$ $" echo "2.sh get \ $ A = $ A from 1.sh" A = C export A echo" 2.sh:\ $ A is $ A "3. experiment 3.1 fork [SQL] PID for 1.sh before exec/source/fork: 25992 1.sh: $ A is B using fork by default... PID for 2.sh: 25993 2.sh get $ A = B from 1.sh 2.sh: $ A is C PID for 1.sh after exec/source/fork: 25992 1.sh: $ A is B 3.2 source [SQL] PID for 1.sh before exec/source/fork: 25994 1.sh: $ A is B using source... PID for 2.sh: 25994 2.sh get $ A = B from 1.sh 2.sh: $ A is C PID for 1.sh after exec/source/fork: 25994 1.sh: $ A is C note: all three PIDs are 25994, and the environmental variables of the subprogram are included. 3.3 exec [SQL] PID for 1.sh before exec/source/fork: 25997 1.sh: $ A is B using exec... PID for 2.sh: 25997 2.sh get $ A = B from 1.sh 2.sh: $ A is C note: The rest of the main program is not executed.