在 shell 中使用临时文件之前,您可以清理它们吗?

Ole*_*nge 4 shell-script

如果我的程序崩溃,我想避免放置临时文件。

UNIX 的美妙之处在于您可以保持文件打开 - 即使在您删除它之后也是如此。

因此,如果您打开文件,立即将其删除,然后进行缓慢处理,那么即使您的程序崩溃,用户也不必清理文件的可能性很高。

在 shell 中,我经常看到类似的东西:

generate-the-file -o the-file
[...loads of other stuff that may use stdout or not...]
do_slow_processing < the-file
rm the-file
Run Code Online (Sandbox Code Playgroud)

但是如果程序崩溃之前rm用户将不得不清理the-file

在 Perl 中,您可以执行以下操作:

open(my $filehandle, "<", "the-file") || die;
unlink("the-file");
while(<$filehandle>) {
  # Do slow processing stuff here
  print;
}
close $filehandle;
Run Code Online (Sandbox Code Playgroud)

然后文件一打开就被删除。

shell 中是否有类似的结构?

Ole*_*nge 5

这是在 csh、tcsh、sh、ksh、zsh、bash、ash、sash 中测试的:

echo foo > the-file
(rm the-file; cat) < the-file | do_slow_processing
Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢:

(rm the-file; do_slow_processing) < the-file
Run Code Online (Sandbox Code Playgroud)

有趣的是,它也适用于 fifos:

mkfifo the-fifo
(rm the-fifo; cat) < the-fifo | do_slow_processing &
echo foo > the-fifo
Run Code Online (Sandbox Code Playgroud)

这是因为读取器被阻塞,直到写入某些内容。