【问题标题】:Counting empty and non-empty files within directories in Bash计算 Bash 目录中的空文件和非空文件
【发布时间】:2021-03-26 15:44:14
【问题描述】:

不幸的是,我没有任何代码作为起点,因为我不知道从哪里开始。我需要创建一个名为 dircheck 的 bash 脚本,它允许用户使用目录路径 (e.g. ./dircheck ~Documents/unit/backup) 运行程序,并让脚本向终端输出以下内容:

输入的目录名称有:
x 空文件,
x 包含数据的文件,
x 空目录,
x 个非空目录

如您所见,我需要输出该目录有多少个空文件,该目录有多少个有数据的文件,有多少个空目录,有多少个有数据的目录。

任何帮助将不胜感激!

【问题讨论】:

  • 查找以下主题:处理命令行参数(位置参数);循环文件(for f in *for loopswildcards);变量和算术;测试文件和目录(test 内置命令)。你会知道下一步该做什么。
  • 您应该查找find(1) command。您应该能够组合 -type-empty-maxdepth 标志来实现您想要的。

标签: bash


【解决方案1】:

正如 cmets 中所建议的,GNU find 可以相当容易地做到这一点。

#!/bin/bash -
echo "$1 has:"
find "$1" -mindepth 1 -type f,d \
  \( -empty -o -printf 'non-' \) -printf 'empty ' \
  \( -type f -printf 'files' -o -printf 'directories' \) \
  -printf '\n' | sort | uniq -c

您只能通过将-maxdepth 1 添加到find 调用来将分析限制在第一级条目。无论如何,它的输出将如下所示:

$ ./foo ./bionic
./bionic has:
      7 empty files
    175 non-empty directories
   2163 non-empty files

【讨论】:

  • 嗨@oguz ismail 感谢您的帮助!有没有办法在不使用 find 命令的情况下做到这一点?
  • 不知道,可能有
【解决方案2】:

我建议这是 dircheck.sh 的另一种方式,通过 bash 函数递归检查给定目录,仅使用 bash 内在语法(shell glob) - 不调用外部命令:

#!/bin/bash
#
# check recursively a directory:
#
function checkDirr() {
  for x in $1/*
  do

    #
    # if it's a sub-directory:
    #
    if [ -d $x ]; then
      #echo "$x is a directory."
      ndirs=$((ndirs + 1))
      #
      # glob all entries in an array:
      #
      entries_array=($x/*)
      #
      # check entries array count:
      #
      if [ ${#entries_array[*]} -eq 0 ]; then
        #echo "empty dir"
        nemptydirs=$((nemptydirs + 1))
      else
        #
        # call recursively myself to check non-empty sub-directory:
        #
        checkDirr $x

      fi

    #
    # otherwise it's a file:
    #
    else
      #echo "$x is a file."
      nfiles=$((nfiles + 1))
      #
      # check empty file:
      #
      if [ ! -s $x ]; then
        nemptyfiles=$((nemptyfiles + 1))
      fi
    fi

  done
}

#
# main():
#
#
# initialize globals:
#
ndirs=0
nfiles=0

nemptydirs=0
nemptyfiles=0

#
# use given directory path or the current directory .:
#
dir0=${1:-.}

#
# set shell nullglob option to avoid dir/* string when dir is empty:
#
shopt -s nullglob

#
# now check recursively the directory:
#
checkDirr $dir0

#
# unset shell nullglob option:
#
shopt -u nullglob

#
# send statistics:
#
echo $dir0 has:
echo
echo $nemptyfiles empty files
echo $((nfiles - nemptyfiles)) files with data
echo $nemptydirs empty directories
echo $((ndirs - nemptydirs)) non-empty directories

    

举个例子

$ dircheck.sh so

也是这样:

2 个空文件

87 个包含数据的文件

3 个空目录

11 个非空目录

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多