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

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

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

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

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

我尝试了一些解决方案,但是每当我满足一个条件时,它就会导致另一个条件失败,或者在不存在文件时失败。

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

答案1

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

以及基于评论的较短版本

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

答案2

我会做一个

if ! ( [[ -s file1 ]] && cmp file1 file2 2>/dev/null 1>&2 )
then
  echo "some text" >file1
  cp file1 file2
fi

解释:

-s file1 如果 file1 存在且不为空,则计算结果为 true。

如果两个文件都存在并且相同,则 cmp 命令将状态代码设置为 0。

在这种情况下,我们不想触及它们,因此我在其前面加上感叹号,以否定该条件。

答案3

使用cmp -s选项:

#!/bin/bash

if ! ( [[ -s file1 ]] && cmp -s file1 file2 )
then
    echo "some text" > file1
    cp file1 file2
fi

-s选项默默地丢弃所有输出到stdoutstderr并仅返回退出状态。

相关内容