一、使用'.'执行
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中然后执行。