249

我有一个名为diff.txt的文件。我想检查它是否为空。

我写了一个类似下面的 bash 脚本,但我无法让它工作。

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

10 回答 10

312

拼写错误很烦人,不是吗?检查你的拼写empty,但也试试这个:

#!/bin/bash -e

if [ -s diff.txt ]; then
        # The file is not-empty.
        rm -f empty.txt
        touch full.txt
else
        # The file is empty.
        rm -f full.txt
        touch empty.txt
fi

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

请注意,正如@Matthias 所建议的那样,我已经交换了empty.txtand的角色。full.txt

于 2012-04-01T13:52:14.340 回答
95
[ -s file.name ] || echo "file is empty"
于 2014-12-30T18:03:15.823 回答
66

[ -s file ] # Checks if file has size greater than 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
于 2017-05-09T03:25:25.670 回答
15

虽然其他答案是正确的,但"-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
于 2017-10-05T11:48:42.653 回答
13

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

if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
  echo "Empty file" 
  ...
fi
于 2019-08-08T15:52:56.570 回答
11

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

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"
于 2020-03-27T06:16:55.900 回答
9

@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
于 2018-04-11T10:52:48.917 回答
3

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

示例 1:基本 if 语句

# 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 为空或不存在,则退出并停止显示。我不止一次将这里的最佳答案误读为相反的意思。

示例 2:作为函数

# -- Check if file is missing /or empty --
# Globals: None
# Arguments: file name
# Returns: Bool
# --
is_file_empty_or_missing() {
    [[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
}
于 2018-04-29T18:27:30.983 回答
3
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
于 2019-05-14T13:25:48.817 回答
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 环境,因此它会破坏你打开的 shell。无论如何,我想我会分享!

于 2019-01-23T16:17:50.377 回答