From: http://hi.baidu.com/yzzcheng/item/1dd92815cfe50e5bf1090ef5
先總結一個表:
exec命令
作用
exec ls
在shell中執行ls,ls結束後不返回原來的shell中了
exec <file
將file中的內容作爲exec的標準輸入
exec >file
將file中的內容作爲標準寫出
exec 3<file
將file讀入到fd3中
sort <&3
fd3中讀入的內容被分類
exec 4>file
將寫入fd4中的內容寫入file中
ls >&4
Ls將不會有顯示,直接寫入fd4中了,即上面的file中
exec 5<&4
創建fd4的拷貝fd5
exec 3<&-
關閉fd3
1. exec 執行程序
雖然exec和source都是在父進程中直接執行,但exec這個與source有很大的區別,source是執行shell腳本,而且執行後會返回以前的shell。而exec的執行不會返回以前的shell了,而是直接把以前登陸shell作爲一個程序看待,在其上經行復制。
舉例說明:
root@localhost:~/test#exec ls
exp1 exp5 linux-2.6.27.54 ngis_post.sh test xen-3.0.1-install
<logout>
root@localhost:~/test#exec >text
root@localhost:~/test#ls
root@localhost:~/test#pwd
root@localhost:~/test#echo "hello"
root@localhost:~/test#exec>/dev/tty
root@localhost:~/test#cat text
exp1
exp5
linux-2.6.27.54
ngis_post.sh
test
text
xen-3.0.1-install
/root/test
hello
root@localhost:~/test#
Exec >text 是將當前shell的標準輸出都打開到text文件中
root@localhost:~/test#cat test
ls
Pwd
root@localhost:~/test#bash
root@localhost:~/test#exec <test
root@localhost:~/test#ls
exp1 exp5 linux-2.6.27.54 ngis_post.sh test text xen-3.0.1-install
root@localhost:~/test#pwd
/root/test
root@localhost:~/test#
root@localhost:~/test#exit #自動執行
2. exec的重定向
先上我們進如/dev/fd/目錄下看一下:
root@localhost:~/test#cd /dev/fd
root@localhost:/dev/fd#ls
0 1 2 255
默認會有這四個項:0是標準輸入,默認是鍵盤。
1是標準輸出,默認是屏幕/dev/tty
2是標準錯誤,默認也是屏幕
255
當我們執行exec 3>test時:
root@localhost:/dev/fd#exec 3>/root/test/test
root@localhost:/dev/fd#ls
0 1 2 255 3
root@localhost:/dev/fd#
看到了吧,多了個3,也就是又增加了一個設備,這裏也可以體會下linux設備即文件的理念。這時候fd3就相當於一個管道了,重定向到fd3中的文件會被寫在test中。關閉這個重定向可以用exec 3>&-。
root@localhost:/dev/fd#who >&3
root@localhost:/dev/fd#ls >&3
root@localhost:/dev/fd#exec 3>&-
root@localhost:/dev/fd#cat /root/test/te
test text
root@localhost:/dev/fd#cat /root/test/test
root tty1 2010-11-16 01:13
root pts/0 2010-11-15 22:01 (192.168.0.1)
root pts/2 2010-11-16 01:02 (192.168.0.1)
0
1
2
255
3
3. 應用舉例:
exec 3<test
while read -u 3 pkg
do
echo "$pkg"
done