shell exec 作用

简介:

shell 执行一个脚本

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


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

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



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

[root@master ~]# cat test.sh 

1
2
#!/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中生效。(为自定义文件描述符而生)


例子:

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



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

本文转自残剑博客51CTO博客,原文链接http://blog.51cto.com/cuidehua/1832038如需转载请自行联系原作者

cuizhiliang
相关文章
|
Shell
shell:使用command判断一个命令是否存在
shell:使用command判断一个命令是否存在
272 0
|
Shell
shell echo用法分析
时间:2017.12.21作者:李强参考:man,info,magedu讲义,万能的internet实验环境:VMware® Workstation 12 Pro ,Centos 6.9,Centos 7.4,SecureCRT Version 8.1.4声明:以下英文纯属个人翻译,英文B级,欢迎纠正,以下内容纯属个人理解,并没有对错,只是参考,盗版不纠,才能有限,希望不误人子弟为好。
672 0
|
Linux Shell Windows

热门文章

最新文章