shell脚本中调⽤其他shell脚本的三种⽅法及区别shell脚本中调⽤其他shell脚本有三种⽅法:
fork:简单的执⾏脚本。如果有执⾏权限可直接执⾏,如果没有权限的话需要在前⾯加上sh。运⾏时会新开⼀个⼦shell执⾏脚本。⼦shell执⾏完成后会返回⽗shell继续执⾏。⼦ Shell 从⽗ Shell 继承环境变量,但是⼦ Shell 中的环境变量不会带回⽗ Shell。
shell脚本返回执行结果source:与fork不同, 在执⾏时不会新开⼀个⼦shell,⽽是在同⼀个shell中执⾏。所以调⽤脚本与被调⽤脚本的变量与环境变量可以互相访问。
exec:与source相同的是,调⽤脚本与被调⽤脚本都是在同⼀个shell中执⾏。并且被调⽤脚本可以访问调⽤脚本中的变量与环境变量。与source不同的是,被调⽤脚本执⾏完成后,调⽤脚本exec之后的内容不会再执⾏。
⽗脚本(调⽤脚本)a.sh:
1#! /bin/bash
2A="a"
3AA="aa"
4export A
5echo "start a.sh PID:$$"
6echo "A in a.sh is $A,AA in a.sh is $AA"
7
8case $1 in
9 fork)
10  echo "--fork b.sh"
11  ./b.sh;;
12 source)
13  echo "--source b.sh"
14  . ./b.sh;;#equals to source ./b.sh
15 exec)
16  echo "--exec b.sh"
17  exec ./b.sh;;
18 *)
19  echo "unknow"
20esac
21echo "A in a.sh is $A,AA in a.sh is $AA"
22echo "a.sh PID:$$ ended"
⼦脚本(被调⽤脚本)b.sh:
1#! /bin/bash
2echo "start b.sh PID:$$"
3echo "get A from a.sh:$A,get AA from a.sh:$AA "
4A="b"
5AA="bb"
6export A
7echo "modify A to b,AA to bb"
8echo "A in b.sh :$A,AA in b.sh:$AA"
9echo "b.sh:PID ended"
分别执⾏以下命令:
1./a.sh fork
2./a.sh source
3./a.sh exec
结果如下:
1start a.sh PID:13306
2  A in a.sh is a,AA in a.sh is aa
3--fork b.sh
4start b.sh PID:13307
5get A from a.sh:a,get AA from a.sh: 6modify A to b,AA to bb
7  A in b.sh :b,AA in b.sh:bb
8  b.sh:PID ended
9  A in a.sh is a,AA in a.sh is aa
10  a.sh PID:13306 ended
1start a.sh PID:13388
2  A in a.sh is a,AA in a.sh is aa
3--source b.sh
4start b.sh PID:13388
5get A from a.sh:a,get AA from a.sh:aa 6modify A to b,AA to bb
7  A in b.sh :b,AA in b.sh:bb
8  b.sh:PID ended
9  A in a.sh is b,AA in a.sh is bb
10  a.sh PID:13388 ended
1start a.sh PID:13416
2  A in a.sh is a,AA in a.sh is aa
3--exec b.sh
4start b.sh PID:13416
5get A from a.sh:a,get AA from a.sh: 6modify A to b,AA to bb
7  A in b.sh :b,AA in b.sh:bb
8  b.sh:PID ended

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。