一个脚本文件调用另一个脚本文件的三种方式l:
① fork;② exec;③ source;
/home/sh1.sh;/home/test/shell1.sh; /home/test/shell2.sh;
用法举例:
① fork:sh1.sh 脚本调用shell1.sh 脚本:在sh1.sh脚本文件中增加一行:/home/test/shell1.sh(shell1.sh脚本有可执行权限);sh /home/test/shell1.sh(shell1.sh脚本没有可执行权限)
shell1.sh脚本调用shell2.sh 脚本:在当前目录下,在shell1.sh脚本中增加一行:./shell2.sh
② exec:sh1.sh 脚本调用shell1.sh 脚本:在sh1.sh脚本文件中增加一行:exec /home/test/shell1.sh
shell1.sh脚本调用shell2.sh 脚本:在当前目录下,在shell1.sh脚本中增加一行:exec shell2.sh
③ source:sh1.sh 脚本调用shell1.sh 脚本:在sh1.sh脚本文件中增加一行:source /home/test/shell1.sh
shell1.sh脚本调用shell2.sh 脚本:在当前目录下,在shell1.sh脚本中增加一行:source shell2.sh
详解:
fork:fork是最普通的,sh1.sh 脚本调用shell1.sh 脚本时terminal会新开一个子shell执行脚本shell1.sh,子shell1.sh执行时父sh1.sh还在。子shell1.sh执行完毕后返回父sh1.sh。子shell1.sh从父sh1.sh中继承环境变量,但子shell1.sh中的环境变量不会带回父sh.sh中。
exec:sh1.sh 脚本调用shell1.sh 脚本时,在同一个shell中执行,使用exec调用shell1.sh后,父脚本sh1.sh文件内容中exec /home/test/shell1.sh之后的内容将不会再执行。
source:sh1.sh 脚本调用shell1.sh 脚本时,在同一个shell中执行,被调用的脚本shell1.sh中声明的变量和环境变量都可以在父脚本sh1.sh中进行获取和使用。
测试脚本(验证区别):
shell1.sh
#!/bin/bash
Variable=12345;
echo "before exec/source/fork: PID for shell1.sh = $$"
export Variable
echo "In shell1.sh:variable Variable=$Variable"
case $1 in
--exec)
echo -e "==> using exec\n"
exec ./shell2.sh;;
--source)
echo -e "==> using source\n"
. ./shell2.sh;;
*)
echo -e "==> using fork by default\n"
./shell2.sh;;
esac
echo "after exec/source/fork: PID for shell1.sh = $$"
echo -e "In shell1.sh:variable Variable=$Variable"
shell2.sh
#!/bin/bash
echo "PID for shell2.sh = $$"
echo "In shell2.sh get variable Variable=$Variable from shell1.sh"
Variable=6789
export Variable
echo -e "In shell2.sh: variable Variable=$Variable"
测试执行: