There are three ways to invoke external scripts when running shell scripts, exec (exec script.sh), source (source script.sh), fork (./script.sh)
EXEC (exec/home/script.sh):
Using Exec to invoke the script is equivalent to executing a command in the current shell, without generating a new process, and the executed script inherits the environment variables of the current shell. However, when the exec call is complete, the current shell ends, and the remaining code is not executed.
Source (source/home/script.sh)
Use source or "." To invoke an external script, it also does not produce a new process, similar to exec, inherits the current shell environment variable, and when the invoked script finishes running, the environment variables and declared variables it owns are retained by the current shell.
Fork (/home/script.sh)
Running the script directly produces a new process and inherits the environment variables and declaration variables of the main script. After execution, the main script does not retain its environment variables and declaration variables.
Main script:
1 #!/bin/sh 2 a=fork 3 4 echo "a is $a" 5 echo "Pid for parent before 2.sh:$$ " 6 case $1 in 7 exec) 8 echo "Using exec" 9 exec ./2.sh ;; 10 source) 11 echo "using sourcing" 12 source ./2.sh ;; 13 *) 14 echo "Using fork" 15 ./2.sh ;; 16 17 esac 18 19 echo "Pid for parent after 2.sh :$$ " 20 21 echo " now main.sh a is $a " 22 echo "$b"
Call Script: 2.sh
1 #!/bin/sh 2 echo "PID for 2.sh:$$" 3 4 echo "2.sh get a from main.sh is $a" 5 6 a=2.sh 7 Export a 8 b=3.sh 9 Ten echo "Now 2.sh A is $a" ~ ~
Execution Result:
[[email protected] home]# ./main.sh execa is mainpid for parent before 2.sh:19026using execpid for 2.sh:190262.sh get a from main.sh is mainnow a is 2.sh[[email protected] home]# ./main.sh sourcea is mainpid for parent before 2.sh:19027using sourcingpid for 2. Sh:190272.sh get a from main.sh is mainnow a is 2.shpid for parent after 2.sh :19027now main.sh a is 2.sh3.sh[[email Protected] home]# ./main.sh forka is mainpid for parent before 2. sh:19028using forkpid for 2.sh:190292.sh get a from main.sh is mainnow a is 2.shpid for parent after 2.sh :19028now main.sh a is main[[email protected] home]#
This article is from the "Hiubuntu" blog, make sure to keep this source http://qujunorz.blog.51cto.com/6378776/1541676