Bash 读/写文件描述符——寻找文件开头 [英] Bash read/write file descriptors -- seek to start of file

查看:21
本文介绍了Bash 读/写文件描述符——寻找文件开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 bash 中使用读/写文件描述符,以便我可以删除文件描述符之后引用的文件,例如:

I tried to use the read/write file descriptor in bash so that I could delete the file that the file descriptor referred to afterward, as such:

F=$(mktemp)
exec 3<> "$F"
rm -f "$F"

echo "Hello world" >&3
cat <&3

但是 cat 命令没有输出.如果我使用单独的文件描述符进行读写,我可以实现我想要的:

but the cat command gives no output. I can achieve what I want if I use separate file descriptors for reading and writing:

F=$(mktemp)
exec 3> "$F"
exec 4< "$F"
rm -f "$F"

echo "Hello world" >&3
cat <&4

打印Hello world.

我怀疑当你从写入切换到读取时 bash 不会自动寻找文件描述符的开头,以下 bash 和 python 代码的组合证实了这一点:

I suspected that bash doesn't automatically seek to the start of the file descriptor when you switch from writing to reading it, and the following combination of bash and python code confirms this:

fdrw.sh

exec 3<> tmp
rm tmp

echo "Hello world" >&3
exec python fdrw.py

fdrw.py

import os  

f = os.fdopen(3)
print f.tell()
print f.read()

给出:

$ bash fdrw.sh
12

$ # This is the prompt reappearing

有没有办法只使用 bash 来实现我想要的?

Is there a way to achieve what I want just using bash?

推荐答案

没有.bash 的重定向没有任何寻求"的概念.它在一个长流中从头到尾读/写(大部分).

No. bash does not have any concept of "seeking" with its redirection. It reads/writes (mostly) from beginning to end in one long stream.

这篇关于Bash 读/写文件描述符——寻找文件开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆