【问题标题】:Bash Scripting - Display number of files and folders in a directoryBash 脚本 - 显示目录中文件和文件夹的数量
【发布时间】:2015-02-17 03:36:58
【问题描述】:

我是 bash 脚本的新手,我发现了这个 example on stackoverflow。现在,这似乎是我需要的,但是我不确定一些事情。

  1. 如何正确修改它以显示下载目录中的文件和文件夹的数量

  2. “$@”是什么意思?

到目前为止我的代码:

cleanPath="/home/someuser/Downloads/*"

if [ -d $cleanPath]; then
    find "$cleanPath" -type f | ls -l $cleanPath | wc -l | echo "Number of files is $@"
    find "$cleanPath" -type d | ls -l $cleanPath | wc -l | echo "Number of directorieis $@"
fi

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    您快到了,但您有一些语法错误(if 语句括号周围需要空格)和其他一些错误。 cleanPath="/home/someuser/Downloads/*" 如果您没有正确引用 "$cleanPath" 之类的 cleanPath 可能会导致问题,因为 shell 会扩展 *,因此您实际上会在下载中获得所有文件和目录的列表(尝试 echo $cleanPath,您会看到)。另外,我不明白为什么要将 find 的输出传递给 ls,ls 甚至不会使用输入,它只会列出所有文件和目录。

    试试这个:

    cleanPath="/home/someuser/Downloads"
    
    if [ -d "$cleanPath" ]; then
      echo "No of files is ""$(find "$cleanPath" -mindepth 1 -type f | wc -l)"
      echo "No of directories is ""$(find "$cleanPath" -mindepth 1 -type d | wc -l)"
    fi
    

    注意这是递归的 - 默认 find 行为。你没有说清楚这是否是你想要的。对于非递归列表:

    cleanPath="/home/someuser/Downloads"
    
    if [ -d "$cleanPath" ]; then
      echo "No of files is ""$(find "$cleanPath" -mindepth 1 -maxdepth 1 -type f | wc -l)"
      echo "No of directories is ""$(find "$cleanPath" -mindepth 1 -maxdepth 1 -type d | wc -l)"
    fi
    

    您还可以使用$@ 作为传递给脚本的所有位置参数的数组表示。

    https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#index-_0024_0040

    注意:-mindepth -maxdepth 不符合 POSIX,这不适用于带有换行符的文件。

    【讨论】:

    • 它有效,但是,它说它们是下载中的 2 个目录,而实际上它只有 1 个目录。这是什么?
    • 第一个是递归的。我也修正了一个错误。我猜你想要第二个例子
    • 完美,第二个就是我想要的。还有一个问题,很抱歉我之前没有提到,是否可以在变量中捕获结果,例如一个变量中的文件数和另一个变量中的目录数?
    • @CharlesWhitfield 将其传递给变量,即VAR=$(...)VAR 必须从行首开始,= 前后不能有空格。
    • @gniourf_gniourf 不,这没有错,不是在我的操作系统上。你真的试过了吗?
    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2014-09-17
    • 2020-10-07
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多