仅当数据时覆盖文件

Hag*_*zen 8 bash

我试图用命令输出覆盖文件,但前提是有任何输出。也就是说,我通常想要

mycommand > myfile
Run Code Online (Sandbox Code Playgroud)

但如果这会被myfile空数据覆盖,我希望保留旧版本的myfile. 我认为使用的东西ifne应该是可能的,a la

mycommand | ifne (cat > myfile) 
Run Code Online (Sandbox Code Playgroud)

但这不起作用......

间接方法

mycommand | tee mytempfile | ifne mv mytempfile myfile
Run Code Online (Sandbox Code Playgroud)

有效,但我认为使用该临时文件不雅。

问:为什么我的第一个想法不起作用?它可以工作吗?或者对于我的原始问题是否有另一个不错的,也许完全不同的解决方案?

ter*_*don 18

您的第一种方法有效,您只需要向ifne(请参阅man ifne)发出命令:

NAME
       ifne - Run command if the standard input is not empty

SYNOPSIS
       ifne [-n] command

DESCRIPTION
       ifne  runs  the  following command if and only if the standard input is
       not empty.
Run Code Online (Sandbox Code Playgroud)

所以你需要给它一个命令来运行。你快到了,tee会工作:

command | ifne tee myfile > /dev/null
Run Code Online (Sandbox Code Playgroud)

如果您的命令不会产生大量数据,如果它足够小以适合变量,您还可以执行以下操作:

var=$(mycommand)
[[ -n $var ]] && printf '%s\n' "$var" > myfile
Run Code Online (Sandbox Code Playgroud)


Kus*_*nda 8

行人解决方案:

tmpfile=$(mktemp)

mycommand >"$tmpfile"
if [ -s "$tmpfile" ]; then
    cat "$tmpfile" >myfile
fi

rm -f "$tmpfile"
Run Code Online (Sandbox Code Playgroud)

即,将输出保存到一个临时文件中,然后测试它是否为空。如果它不为空,请将其内容复制到您的文件上。最后,删除临时文件。

我使用cat "$tmpfile" >myfile而不是cp "$tmpfile" myfile(或mv)来获得与您从 中获得的效果相同的效果mycommand >myfile,即截断现有文件并保留所有权和权限。

如果$TMPDIR(由 使用mktemp)在内存安装的文件系统上,那么除了写入myfile. 此外,它比使用ifne.