Bash 为什么管道读取和写入同一个文件会导致一个空白文件?

Bash 为什么管道读取和写入同一个文件会导致一个空白文件?,bash,Bash,我有一个文本文件,其中有几行我想排序。此文件名为somefile cat somefile | sort 结果将某些已排序的输出发送到stdout cat somefile > anotherfile 导致cat somefile的输出被写入另一个文件 然而 cat somefile | sort > somefile 导致somefile为空 为什么会这样?我希望somefile被发送到stdout,重定向到sort程序,该程序将排序后的输出发送到stdout,然后将其写入s

我有一个文本文件,其中有几行我想排序。此文件名为
somefile

cat somefile | sort
结果将某些已排序的输出发送到stdout

cat somefile > anotherfile
导致
cat somefile
的输出被写入另一个文件

然而

cat somefile | sort > somefile
导致
somefile
为空


为什么会这样?我希望
somefile
被发送到stdout,重定向到sort程序,该程序将排序后的输出发送到stdout,然后将其写入
somefile
重定向首先清空目标文件,因此无需进行cat或排序。

管道中的进程是并行执行的,不是按顺序的

cat somefile | sort
因此,
cat somefile | sort>somefile
所做的是:

同时运行
cat
sort
,并将
cat
stdout
连接到
sort
stdin
sort
连接到为
somefile
打开的文件描述符

cat somefile | sort

shell需要为
设置重定向,然后才能运行
cat
sort
。在此过程中,它对每个重定向使用
open()
dup2()
系统调用。因此,在对
open()
系统调用将其截断之前,
cat
没有机会读取该文件。

这只能使用sort命令来完成

sort -o somefile somefile
否则,您将不得不对tmp文件运行排序

sort somefile > tmpfile && mv tmpfile somefile