首页 > 系统服务 > 详细

Linux SHELL之source与.的区别

时间:2015-09-10 16:06:25      阅读:234      评论:0      收藏:0      [点我收藏+]

一、使用‘.‘执行

1. 文件内容:

a.sh

#!/bin/sh

a=2

echo a=$a

b.sh

#!/bin/sh

./a.sh

echo a.sh: a=$a

2. 添加可执行权限
# chmod +x a.sh b.sh

3. 运行
# ./b.sh 
a=2
a.sh: a=

可以看出b.sh中的a并没有获取a.sh中的a变量,只是将a.sh给执行了一遍

二、使用source执行

1. 文件内容:

a.sh

#!/bin/sh

a=2

echo a=$a

b.sh

#!/bin/sh

source ./a.sh

echo a.sh: a=$a

2. 添加可执行权限
# chmod +x a.sh b.sh

3. 运行
# ./b.sh 
a=2
a.sh: a=2

可见b.sh中获取到了a.sh中的a变量

三、结论

其实‘.‘只是将shell脚本执行了一遍,而source是将shell脚本中的代码添加到当前脚本中,类似与c语言中的include。

我们用bash -x看下执行详细的信息

1) ‘.‘的方式

# sh -x b.sh 
+ ./a.sh
a=2
+ echo a.sh: a=
a.sh: a=

2) source的方式

# sh -x b.sh 
+ source ./a.sh
++ a=2
++ echo a=2
a=2
+ echo a.sh: a=2
a.sh: a=2

可以看出‘.‘的方式只是执行了a.sh并输出了a.sh的结果a=2; 而source的方式是将a.sh的代码添加到b.sh中然后执行。


Linux SHELL之source与.的区别

原文:http://my.oschina.net/u/2426299/blog/504501

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!