检查文件是否存在,不为空且等于另一个

Fre*_*edo 0 scripting files

我想检查一个文件是否存在,不为空并且等于另一个文件。如果是这样,什么都不做。

如果它们不相等,则用cat "some text".

如果它们不存在或为空,则还创建文件 cat some text

我尝试了一些解决方案,但是每当我得到一个条件正确时,它就会使另一个失败,或者在不存在文件时失败。

解决这个问题的最干净的方法是什么?所有这些都使用 bash?

Hau*_*ing 5

if [ -f file1 ] && [ -s file1 ] && [ -f file2 ] && [ -s file2 ] &&
    cmp file1 file2 &>/dev/null; then
    : do nothing in this case only
else
    echo "some text" >file1
    echo "some text" >file2 # or cp file1 file2
fi
Run Code Online (Sandbox Code Playgroud)

和一个更短的版本,基于评论

if [ -s file1 ] && cmp file1 file2 &>/dev/null; then
    : do nothing in this case only
else
    echo "some text" >file1
    echo "some text" >file2 # or cp file1 file2
fi
Run Code Online (Sandbox Code Playgroud)