在运行shell脚本时候,有三种方式来调用外部的脚本,exec(exec script.sh)、source(source script.sh)、fork(./script.sh)
exec(exec /home/script.sh):
使用exec来调用脚本相当于在当前shell执行了一条命令,不会产生新的进程,被执行的脚本会继承当前shell的环境变量。但是当exec调用完毕后,当前shell也会结束,剩下的代码不会执行。
source(source /home/script.sh)
使用source或者“.”来调用外部脚本,同样不会产生新的进程,与exec类似,继承当前shell环境变量,而且被调用的脚本运行结束后,它拥有的环境变量和声明变量会被当前shell保留。
fork(/home/script.sh)
直接运行脚本,会产生新的进程,并且继承主脚本的环境变量和声明变量。执行完毕后,主脚本不会保留其环境变量和声明变量。
主脚本:
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"
调用脚本: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 10 echo "now 2.sh a is $a" ~ ~
执行结果:
[[email protected] home]# ./main.sh exec a is main PID for parent before 2.sh:19026 using exec PID FOR 2.SH:19026 2.sh get a from main.sh is main now a is 2.sh [[email protected] home]# ./main.sh source a is main PID for parent before 2.sh:19027 using sourcing PID FOR 2.SH:19027 2.sh get a from main.sh is main now a is 2.sh PID FOR parent after 2.sh :19027 now main.sh a is 2.sh 3.sh [[email protected] home]# ./main.sh fork a is main PID for parent before 2.sh:19028 using fork PID FOR 2.SH:19029 2.sh get a from main.sh is main now a is 2.sh PID FOR parent after 2.sh :19028 now main.sh a is main [[email protected] home]#
Linux shell脚本中调用另一个shell(exec、source、fork)
时间: 2024-10-03 14:00:52