標籤:source fork exec 呼叫指令碼 shell
在運行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 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]#
本文出自 “hiubuntu” 部落格,請務必保留此出處http://qujunorz.blog.51cto.com/6378776/1541676