如何在Bash中检查文件是否为空?

时间:2012-04-01 13:41:06

标签: bash if-statement file-handling is-empty

我有一个名为diff.txt的文件。想检查它是否为空。做过这样的事情却无法让它发挥作用。

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

10 个答案:

答案 0 :(得分:188)

拼写错误很刺激,不是吗?检查您的empty拼写,但也请尝试:

#!/bin/bash -e

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

我非常喜欢shell脚本,但是它的一个缺点是,当你拼错时,shell无法帮助你,而像你的C ++编译器这样的编译器可以帮助你。

顺便提一下,我已经交换了empty.txtfull.txt的角色,正如@Matthias建议的那样。

答案 1 :(得分:57)

[ -s file.name ] || echo "file is empty"

答案 2 :(得分:38)

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

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

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

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

答案 3 :(得分:6)

虽然其他答案都是正确的,但即使文件不存在,使用"-s"选项也会显示文件为空。
通过添加此附加检查"-f"以查看文件是否存在,我们确保结果正确。

if [ -f diff.txt ]
then
  if [ -s diff.txt ]
  then
    rm -f empty.txt
    touch full.txt
  else
    rm -f full.txt
    touch empty.txt
  fi
else
  echo "File diff.txt does not exist"
fi

答案 4 :(得分:4)

@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

答案 5 :(得分:3)

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

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"

答案 6 :(得分:1)

许多答案都是正确的,但我觉得它们可能更完整  /简单化等,例如:

# BASH4+ example on Linux :

typeset read_file="/tmp/some-file.txt"
if [ ! -s "${read_file}" ]  || [ ! -f "${read_file}" ] ;then
    echo "Error: file (${read_file}) not found.. "
    exit 7
fi

如果$ read_file为空或没有,则退出该节目。我不止一次误读了最顶层的答案,意思相反。

答案 7 :(得分:1)

要检查文件是否为空或仅包含空白,可以使用grep:

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

答案 8 :(得分:0)

我是来这里寻找如何删除空__init__.py文件的,因为它们在Python 3.3+中是隐式的,并最终使用:

find -depth '(' -type f  -name __init__.py ')' -print0 |
  while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done

也(至少在zsh中)使用$ path作为变量也会破坏$ PATH env,因此会破坏打开的shell。无论如何,以为我会分享!

答案 9 :(得分:0)

[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
相关问题