Shell 脚本调用另一个 Shell 脚本的三种方式:
- fork (/directore/script2.sh)
- 该方式会重新启动一个shell来执行script2.sh
- 新的shell执行script2.sh时,主shell依旧存在
- 新的shell会继承主shell的环境变量,新的shell执行完后不会将自己的环境变量交付给主shell
- 新的shell执行完后,控制权交回给主shell,继续执行主shell后面的code
- source (source /directory/script2.sh)
- 该方式不会重新启动一个shell来执行script2.sh
- script2.sh 直接在主shell中执行
- script2.sh 继续使用在主shell存在的环境变量
- 执行完script2.sh之后,继续执行主shell后面的code
- exec (exec /directory/script2.sh)
- 该方式不会重新启动一个shell来执行script2.sh
- script2.sh 直接在主shell中执行
- script2.sh 继续使用在主shell存在的环境变量
- 执行完script2.sh之后,不再执行主shell后面的code
可以通过下面这两个脚本来体会三种调用方式的不同:
main.sh
1 #!/bin/bash
2
3
4 A=B
5
6
7 echo "INFO: PID of main.sh before exec / source / fork: $$"
8
9
10 export A
11 echo "INFO: main.sh: \$A: $A"
12
13
14 case $1 in
15 exec)
16 echo "INFO: Shell call usage of exec"
17 exec ./called.sh ;;
18 source)
19 echo "INFO: Shell call usage of source"
20 . ./called.sh ;;
21 *)
22 echo "INFO: Shell call usage of default(fork)"
23 ./called.sh ;;
24 esac
25
26
27 echo "INFO: PID of main.sh after exec / source / fork: $$"
28 echo "INFO: main.sh: \$A: $A"
called.sh
1 #!/bin/bash
2
3
4 echo "INFO: PID of called.sh: $$"
5
6
7 echo "INFO: called.sh getS \$A = $A from main.sh"
8
9
10 A=C
11 export A
12 echo "INFO: called.sh: \$A: $A"
执行结果:
boyang@localhost: 17:43 ~/boyang/temp # ./main.sh
INFO: PID of main.sh before exec / source / fork:23255
INFO: main.sh: $A: B
INFO: Shell call usage of default(fork)
INFO: PID of called.sh: 23262
INFO: called.sh getS $A = B from main.sh
INFO: called.sh: $A: C
INFO: PID of main.sh after exec / source / fork:23255
INFO: main.sh: $A: B
boyang@localhost: 17:43 ~/boyang/temp # source ./main.sh
INFO: PID of main.sh before exec / source / fork:23286
INFO: main.sh: $A: B
INFO: Shell call usage of source
INFO: PID of called.sh: 23286
INFO: called.sh getS $A = B from main.sh
INFO: called.sh: $A: C
INFO: PID of main.sh after exec / source / fork:23286
INFO: main.sh: $A: C
boyang@localhost: 17:43 ~/boyang/temp # exec ./main.sh
INFO: PID of main.sh before exec / source / fork:23300
INFO: main.sh: $A: B
INFO: Shell call usage of exec
INFO: PID of called.sh: 23300
INFO: called.sh getS $A = B from main.sh
INFO: called.sh: $A: C
转自:神勇小白鼠的博客
在shell脚本中调用另一个脚本的三种不同方法(fork, exec, source) - 鼠穴 - OSCHINA - 中文开源技术交流社区