linux exec用法

exec在shell中使用时执行不会返回当前的shell, 而是和之前的shell独立,就像是两个程序,但是不会产生新的pid。

exec命令如下:

exec ls

在shell中执行ls,ls结束后不返回原来的shell中了

exec <file

将file中的内容作为exec的标准输入

exec >file

将file中的内容作为标准写出

exec 3<file

将file读入到fd3中

exec 4>file

将写入fd4中的内容写入file中

ls >&4
Ls将不会有显示,直接写入fd4中了,即上面的file中

exec 5<&4

创建fd4的拷贝fd5

exec 3<&-

关闭fd3


示例1如下:

[root@localhost jexusbak]# 
[root@localhost jexusbak]# pwd
/root/jexusbak
[root@localhost jexusbak]# ls
default  fanti  qqxdlq2  souhu  xdlq2  xdlq2ceshi  xunlei
[root@localhost jexusbak]# bash
[root@localhost jexusbak]# exec > test
[root@localhost jexusbak]# ls
[root@localhost jexusbak]# pwd
[root@localhost jexusbak]# exit
exit
[root@localhost jexusbak]# cat test
default
fanti
qqxdlq2
souhu
test
xdlq2
xdlq2ceshi
xunlei
/root/jexusbak
[root@localhost jexusbak]# 


如上:在执行exec >ls后,再输入命令ls,pwd不会输出到当前 shell中,而是重定向到test这个文件中,这些都是在一个shell中实现的,并不会产生新pid;关闭的exec请使用

exec <&-


示例2如下:

[root@localhost jexusbak]# cat test 
ls
pwd
[root@localhost jexusbak]# bash
[root@localhost jexusbak]# exec < test
[root@localhost jexusbak]# ls
default  fanti  qqxdlq2  souhu  test  xdlq2  xdlq2ceshi  xunlei
[root@localhost jexusbak]# pwd
/root/jexusbak
[root@localhost jexusbak]# exit
[root@localhost jexusbak]# 


如上:我们test中原来有ls,pwd两行命令,我们将test中的内容作为exec的标准输入,则会在屏幕上依次执行这两个命令。



综上所述,我们可以使用此种方法打印日志,而不必逐行命令加重定向生成。

如:exec 100>/tmp/test

exec 1>&100

exec 2>&1

exec 100<&-最后关闭fd,我们要有关闭文件描述符的习惯。


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值