shell 执行一个脚本

source 一个脚本 Execute commands from a file in the current shell.


以上两者还是比较好区分的

sh 执行会生成一个新的子shell 去执行里面的脚本,执行完毕后,返回到父进行当中。而source会把脚本内容加载到本shell进程中执行。



看看以下这个例子就知道了。

[root@master ~]# cat test.sh 

#!/bin/bash
a=1


[root@master ~]# sh test.sh 

[root@master ~]# echo $a


[root@master ~]# source  test.sh 

[root@master ~]# echo $a

1


#在source执行脚本的作用下,a变量是在本shell环境中的。而sh 执行test.sh的变量再子shell中,当脚本执行完成后,回到父shell,所以a变量为空(子shell的环境变量不被父shell继承)


source常用 source /etc/profile



【讲讲一个难点关于exec】

help exec查看官方帮助信息

  Replace the shell with the given command. 

    Execute COMMAND, replacing this shell with the specified program.

    ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,

    any redirections take effect in the current shell.



解释exec有两个功能

  1. 取代当前的shell,通过给出的命令程序。即命令执行完成后,会退出本shell了。

[andy@master ~]$ echo $SHLVL

1

[andy@master ~]$ exec ls

scripts

...退出了终端


注:exec 执行了ls命令程序取代了shell进程,当ls执行完成后,退出了。所以会退出终端


2. 当exec后面没有接命令的话,任何冲执行的重定向会在当前shell中生效。(为自定义文件描述符而生)


例子:

#/bin/bash
exec 3< /etc/issue
while read -u3 line; do
    echo $line
done
exec 3>&-



注:read -u3 line 的意思是从文件描述符3中读取光标所在的行赋值给line这个变量。