zl程序教程

您现在的位置是:首页 >  其他

当前栏目

linux shell脚本sh和source区别

2023-02-18 16:48:39 时间

shell中使用source xxx.sh ,是直接运行xxx.sh的命令,不创建子shell,而sh则创建子shell,子shell里面 的变量父shell无法使用,对环境变量的修改也不影响父shell。父shell中的局部变量,子shell也无法使用,只有父shell的环境变量, 子shell能够使用。

sh 创建了子shell和当前的shell并行执行,子shell中执行,脚本设置的变量不会影响当前shell。一旦子Shell中的执行完毕,此子Shell随即结束,回到父Shell中,不会影响父Shell原本的环境。

sh执行脚本

source执行脚本

还有个办法可以在父shell和子shell中分别加上 echo $SHLVL ,显示当前运行层级,可以明显的看出来:

两种执行层级不同

[root@bogon home]# cat father.sh

#!/bin/bash

echo "father shell"

echo $SHLVL

echo "father shell"

echo "source son shell"

source son.sh

echo "source son shell"

echo "sh son shell"

sh son.sh

echo "sh son shell"

[root@bogon home]# cat son.sh

#!/bin/bash

echo $SHLVL