我有一个叫diff。txt的文件。我想看看它是不是空的。

我写了一个bash脚本,类似于下面,但我不能让它工作。

if [ -s diff.txt ]
then
        touch empty.txt
        rm full.txt
else
        touch full.txt
        rm emtpy.txt
fi

当前回答

要检查文件是否为空或只有空格,可以使用grep:

if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
  echo "Empty file" 
  ...
fi

其他回答

[-s file] #检查文件大小是否大于0

[ -s diff.txt ] && echo "file has something" || echo "file is empty"

如果需要,这将检查当前目录中的所有*.txt文件;并报告所有空文件:

for file in *.txt; do if [ ! -s $file ]; then echo $file; fi; done

检查文件是否为空的最简单的方法:

if [ -s /path-to-file/filename.txt ]
then
     echo "File is not empty"
else
     echo "File is empty"
fi

你也可以用单行写:

[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"

要检查文件是否为空或只有空格,可以使用grep:

if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
  echo "Empty file" 
  ...
fi

@geedoubleya的答案是我最喜欢的。

然而,我更喜欢这样

if [[ -f diff.txt && -s diff.txt ]]
then
  rm -f empty.txt
  touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
  rm -f full.txt
  touch empty.txt
else
  echo "File diff.txt does not exist"
fi
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"