用source执行脚本文件,执行过程不另开进程,脚本文件中设定的变量在当前shell中可以看到; source与. 功能相同。
用sh执行脚本文件,是在当前进程另开子进程来执行脚本命令,脚本文件中设定的变量在当前shell中不能看到。
shell1.sh
echo "shell1 begin"
while [ 1==1 ]
do
echo 'shell1 while before'
exit 255
echo $?' while1'
echo 'shell1 while end'
break
done
echo $?' shell1 end'
shell2.sh
echo "shell2 begin"
while [ 1==1 ]
do
echo 'shell2 while before'
sh shell1.sh
var=$?
echo 'get value from shell1.sh '$var
if [ "$var"==255 ]
then
exit 255
fi
echo 'shell2 while end'
done
echo $?'shell2 end'
- source shell1.sh
用户source执行脚本,脚本中有 exit/break, 会直接退出会话连接
2. sh shell1.sh
用sh执行时,脚本中有 exit/break, 会退出当前脚本,但不会退出系统连接
3. sh shell2.sh
用sh调用脚本,脚本中嵌套调用另一个脚本, 里面的脚本存在 break/exit时,会退出里层脚本,并且外层脚本会继续往后执行。(注:因为sh执行时会另开子进程,所以退出时,是关掉子进程)
如果用source,则不会。