繁体   English   中英

计算指定目录中的所有文件/目录-bash / shell脚本

[英]Counting All FIles/Directories in a Specified Directory - bash/shell scripting

成品用于递归计数指定目录中的所有内容,如果没有输入任何参数,则为当前目录。 现在,我只是想让它计算指定目录中的任何内容。 我很难获得最后的声明来计算任何东西。 它将在目录中回显0个文件。

谁能给我提示吗? 我仍然是初学者,所以请放心,谢谢!

#!/bin/bash
#A shell script program that counts recursively how many directories/files exist in a given directory.

declare -i COUNT=0
declare -i COUNT2=0
#The script will treat COUNT as an integer that is 0 until modified.
if [ "$#" -eq "0" ]
    then

        for i in *
        do
            ((COUNT++))
        done
    ((COUNT--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT files and/or directories in the current directory here."
fi

if [[ -d $1 ]]
    then
        for i in $1
        do
            ((COUNT++))
        done
    ((COUNT--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT files and/or directories in $1."
fi

if [[ -d $2 ]]
    then
        for i in $2
        do
            ((COUNT2++))
        done
    ((COUNT2--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT2 files and/or directories in $2."
fi
exit 0

首先,您可以使用单线工作:

find . | wc -l  

find . 表示“在当前目录和所有子目录中搜索”。 由于没有其他参数,它将简单列出所有内容。 然后,我使用管道和wc ,它代表“字数统计”。 -l选项的意思是“仅输出行数”。

现在,对于您的代码,这里有一些提示。 首先,我不太了解为什么要重复三次代码(分别为0,$ 1和$ 2)。 您可以简单地执行以下操作:

dir="$1"
if [ -z "$dir" ]; then dir="."; fi

您将命令行参数的值存储在$ dir中,如果未提供任何参数(-z表示“为空”),则将默认值分配给dir。

for i in $1如果$1是目录路径,则$1中的for i in $1将不起作用。 因此,您可以使用

for i in $(ls $dir)

另外,在您的代码中,您无需递归计数。 是自愿的还是您不知道如何进行?

暂无
暂无

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

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