天天看點

shell exec 作用

shell 執行一個腳本

source 一個腳本 Execute commands from a file in the current shell.

以上兩者還是比較好區分的

sh 執行會生成一個新的子shell 去執行裡面的腳本,執行完畢後,傳回到父進行當中。而source會把腳本内容加載到本shell程序中執行。

看看以下這個例子就知道了。

[root@master ~]# cat test.sh 

<code>#!/bin/bash</code>

<code>a=1</code>

[root@master ~]# sh test.sh 

[root@master ~]# echo $a

[root@master ~]# source  test.sh 

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有兩個功能

取代目前的shell,通過給出的指令程式。即指令執行完成後,會退出本shell了。

[andy@master ~]$ echo $SHLVL

[andy@master ~]$ exec ls

scripts

...退出了終端

注:exec 執行了ls指令程式取代了shell程序,當ls執行完成後,退出了。是以會退出終端

2. 當exec後面沒有接指令的話,任何沖執行的重定向會在目前shell中生效。(為自定義檔案描述符而生)

例子:

<code>#/bin/bash</code>

<code>exec</code> <code>3&lt; </code><code>/etc/issue</code>

<code>while</code> <code>read</code> <code>-u3 line; </code><code>do</code>

<code>    </code><code>echo</code> <code>$line</code>

<code>done</code>

<code>exec</code> <code>3&gt;&amp;-</code>

注:read -u3 line 的意思是從檔案描述符3中讀取光标所在的行指派給line這個變量。

本文轉自殘劍部落格51CTO部落格,原文連結http://blog.51cto.com/cuidehua/1832039如需轉載請自行聯系原作者

cuizhiliang