- 三种调用方式:
fork(./script.sh)、exec(exec script.sh)、source(source script.sh)
- fork
fork 是最普通的, 就是直接在脚本里面用parh/xxx.sh来调用 xxx.sh这个脚本,比如:
```
/home/soft/script/StartJars.sh
```
运行的时候会以当前shell为父进程,产生新的子进程,子进程执行的时候,父进程还在。子进程从父进程继承环境变量,子进程执行完毕后返回父进程,但是子进程中的环境变量和声明变量不会带回父进程。
- exec
exec 与 fork 不同,不需要新开一个子进程来执行被调用的脚本,被调用的脚本与父脚本在同一个进程内执行,被执行的脚本会继承当前shell的环境变量,但是使用 exec 调用一个新脚本以后, 父脚本中 exec 行之后的内容就不会再执行了。
- source
不会产生新的进程,继承当前shell环境变量,而且被调用的脚本运行结束后,它拥有的环境变量和声明变量会被当前shell保留,类似将调用脚本的内容复制过来直接执行,执行完毕后原主shell继续运行。
- 例子
hello.sh
echo “hello”
echo "hello.sh:$$"
输出结果为:
hello
hello.sh:18003
hello_fork.sh
echo "PID for parent hello_fork.sh:$$"
./hello.sh
echo “using fork”
echo "PID for parent hello_fork.sh:$$"
输出结果为:
PID for parent hello_fork.sh:18076
hello
hello.sh:18077
using fork
PID for parent hello_fork.sh:18076
hello_exec.sh
echo "PID for parent hello_exec.sh:$$"
exec ./hello.sh
echo “using exec”
echo "PID for parent hello_exec.sh:$$"
输出结果为:
PID for parent hello_exec.sh:18104
hello
hello.sh:18104
source_source.sh
echo "PID for parent source_source.sh:$$"
exec ./hello.sh
echo “using source”
echo "PID for parent source_source.sh:$$"
输出结果为:
PID for parent source_source.sh:18222
hello
hello.sh:18222
using source
PID for parent source_source.sh:18222