摆事实
脚本准备
脚本名称 name.sh call-name.sh
相互调用关系见下面的代码
[root@server maldetect-1.6.4]# cat name.sh call-name.sh
#!/bin/bash
myname="suyi-vs-shuyi"
yourname="miaorenfeng"
echo "$myname + $yourname"
#!/bin/bash
echo "============sh 运行脚本========================="
echo "Who are you?"
sh name.sh
echo "I'm $myname"
echo "============source运行脚本======================"
echo "Who am I?"
source $PWD/name.sh
echo "You are $yourname"
echo "=============exec运行脚本======================="
exec $PWD/name.sh >./names.txt
echo `ps -e | grep name.sh | awk '{print $1}'`
echo "My name is $myname ,your name is $yourname "
修改权限
为了后面执行不会提示权限问题(特别是name.sh),执行下面的命令修改下权限(可以先查看name.sh没有执行权限,有了可以省略该步骤):
chmod + name.sh call-name.sh
脚本执行
[root@server maldetect-1.6.4]# sh call-name.sh
============sh 运行脚本=========================
Who are you?
suyi-vs-shuyi + miaorenfeng
I'm
============source运行脚本======================
Who am I?
suyi-vs-shuyi + miaorenfeng
You are miaorenfeng
=============exec运行脚本=======================
[root@server maldetect-1.6.4]# cat names.txt
suyi-vs-shuyi + miaorenfeng
[root@server maldetect-1.6.4]#
由事实讲道理
观察以上的脚本及运行结果,理解sh、source、exec调用脚本后的不同效果
调用方式 | 效果说明 | 程序验证 |
---|---|---|
sh(bash、./) | sh、bash、./调用效果相同,调用之后都会产生子shell,父脚本中不能引用子shell中的变量 | 从返回值中就可以看到效果,I’m 后面的值为空,说明引用了一个不存在的变量 |
source | 调用脚本后不会产生子shell,都在同一个shell中,可以引用被调用脚本中的变量 | 从返回值中就可以看到效果,You are miaorenfeng,说明变量使用正常 |
exec | 脚本执行后不会再继续执行父脚本中的其他命令 | 执行脚本以后之后的语句并没有执行,说明使用exec name.sh后将不再执行之后的语句,但是cat names.txt 中是有值的,说明exec调用脚本正常,符合预期 |