等待 stdout 流完成,然后将其内容添加到文件中

zan*_*ona 9 shell bash io-redirection

我试图在 bash 中运行一个命令,其中我有一个command 1通过 stdin 接受大量内容然后将该内容输出到 a 的命令file.txt,但是,command 1生成内容流并且显然file.txtcommand 1启动后立即创建,然后在command 1完成后更新具有正确的输出。

echo 'a lot of content' | command 1 > file.txt
Run Code Online (Sandbox Code Playgroud)

问题是我只想创建或触摸file.txt一次command 1完全完成。

有什么方法可以实现吗?

编辑:

用例:我使用的是每次文件更改时都会刷新的 Web 开发服务器,因此我在真正更新文件之前进行了一些预处理。

上面命令的问题是,如果文件被更新或创建空内容,服务器会立即刷新,有一个空页面,所以我真的想等待后期处理完成(假设大约需要 4 秒)和只有file.txt这样才能在页面上正确呈现它。

因此,我只需要在这里运行一个命令,即command 1file.txt更新后,我的 Web 开发服务器将自动刷新。

hee*_*ayl 15

sponge从 GNU使用moreutils

echo 'a lot of content' | command 1 | sponge file.txt
Run Code Online (Sandbox Code Playgroud)

或者使用临时文件。


ter*_*don 15

最简单的解决方案可能sponge@heemayl 建议的。或者,您可以执行以下操作:

command > tmpfile && mv tmpfile watched_file
Run Code Online (Sandbox Code Playgroud)

这将导致command将其输出保存在 中tmpfile,只有watched_file在命令退出并且成功退出后,才会将其重命名为(您的服务器设置为监视的文件)。要在失败时重命名它,请使用:

command > tmpfile; mv tmpfile watched_file
Run Code Online (Sandbox Code Playgroud)