shell built in - exec command

shell的内建命令exec将并不启动新的shell,而是用要被执行命令替换当前的shell进程,并且将老进程的环境清理掉,而且exec命令后的其它命令将不再执行。
因此,如果你在一个shell里面,执行exec ls那么,当列出了当前目录后,这个shell就自己退出了,因为这个shell进程已被替换为仅仅执行ls命令的一个进程,执行结束自然也就退出了。为了避免这个影响我们的使用,一般将exec命令放到一个shell脚本里面,用主脚本调用这个脚本,调用点处可以用bash a.sh,(a.sh就是存放该命令的脚本),这样会为a.sh建立一个sub shell去执行,当执行到exec后,该子脚本进程就被替换成了相应的exec的命令。
source命令或者".",不会为脚本新建shell,而只是将脚本包含的命令在当前shell执行。
不过,要注意一个例外,当exec命令来对文件描述符操作的时候,就不会替换shell,而且操作完成后,还会继续执行接下来的命令。
exec 3<&0:这个命令就是将操作符3也指向标准输入。

另外,这个命令还可以作为find命令的一个选项,如下所示:
(1)在当前目录下(包含子目录),查找所有txt文件并找出含有字符串"bin"的行
find ./ -name "*.txt" -exec grep "bin" {} \;
(2)在当前目录下(包含子目录),删除所有txt文件
find ./ -name "*.txt" -exec rm {} \;

先总结一个表:
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

[color=red]More aritcle about linux Link:http://note.sdo.com/u/_mr.jian/[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值