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

时间:2016-01-24 00:02:53

标签: bash shell unix 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

1 个答案:

答案 0 :(得分:4)

首先,你可以用单行做你想做的事:

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将无效。相反,您可以使用

for i in $(ls $dir)

此外,在您的代码中,您不会递归计算。它是自愿的还是你不知道如何继续?

相关问题