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