繁体   English   中英

Bash脚本-显示目录中文件和文件夹的数量

[英]Bash Scripting - Display number of files and folders in a directory

我是bash脚本的新手,我在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

您快到这里了,但是您会遇到一些语法错误(if语句括号内需要空格)和其他一些错误。 如果由于外壳扩展*而没有正确引用cleanPath之类的"$cleanPath"cleanPath="/home/someuser/Downloads/*"可能会引起问题,因此您实际上会获得Downloads中所有文件和目录的列表(尝试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,并且不适用于带有换行符的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM