用于计算文件数的bash递归函数

用于计算文件数的bash递归函数,bash,shell,Bash,Shell,所以我想制作一个shell脚本,计算文件夹中所有隐藏的文件、别名和子目录。问题是,我创建的函数的递归调用没有超出第一个深度级别: function recursive_func() { current=$1 echo $current for thing in $(ls -A $current) do if [ -d $current/$thing ] then let subd++

所以我想制作一个shell脚本,计算文件夹中所有隐藏的文件、别名和子目录。问题是,我创建的函数的递归调用没有超出第一个深度级别:

function recursive_func()
{
    current=$1
    echo $current
    for thing in $(ls -A $current)
    do
        if [ -d $current/$thing ]
        then
            let subd++
            recursive_func $current/$thing
        elif [ -L $thing ] ; then
            let symlinks++
        elif [ -f $thing -a ${thing:0:1} == "." ] ; then
            let hidden++
        fi
    done
}
然而,我的一位同事成功地做到了这一点,看起来是这样的:

function recursive_func()
{
    echo $1
    for thing in $(ls -A $1)
    do
        path=$1/$thing
        if [ -d $path ]
        then
            let subd++
            recursive_func $path
        elif [ -L $path ] ; then
            let symlinks++
        elif [ -f $path-a ${thing:0:1} == "." ]; then
            let hidden++
        fi
    done
}
我说不出为什么第二个版本有效,但我的版本不行。有什么帮助吗

编辑:
问题是,
current
是全局的,因此在每次递归调用之后,
for
循环中其余迭代的值都是错误的。通过将
local
添加到
current
前面,或者只使用
$1
来修复它。

最好使用find来避免递归调用,并使用wc-l来计算输出行数

在要搜索的文件夹中尝试以下操作:

find -mindepth 1 -name '.*'
find -mindepth 1 -name '.*' | wc -l

current
是一个全局变量,每次递归调用后,for循环中其余迭代的值都是错误的。通过在current前面添加local或使用$1来修复此问题

function recursive_func()
{
    local current=$1
    echo $current
    for thing in $(ls -A $current)
    do
        if [ -d $current/$thing ]
        then
            let subd++
            recursive_func $current/$thing
        elif [ -L $thing ] ; then
            let symlinks++
        elif [ -f $thing -a ${thing:0:1} == "." ] ; then
            let hidden++
        fi
    done
}

试试这个

recursive_func () {
    shopt -s dotglob
    for item in $1/*; {
        fname=$(basename $item)
        [[ -L $item ]] && ((symlinks++))
        [[ ${fname::1} = '.' ]] && ((hidden++))
        [[ -d $item ]] && { ((subd++)); recursive_func "$item"; }
    }
    shopt -u dotglob
}
第一个命令列出目录中的所有文件,并将它们放在长格式中,以便每个文件占用一行。第二个命令计算行数


道歉;我刚刚意识到您需要递归。

看起来最重要的区别是
路径=$1/$thing
和检查
$path
而不是
$thing
。但是为了给你更多的帮助,你需要明确“不起作用”的含义。你有错误吗?你的计数都是
0
,还是什么?我有一个限制,不能使用
find
ls-R
。因为你使用的是Bash,我认为这是最好的方法。你遍历到目录的符号链接吗?我有一个限制,不能使用
find
ls-R
。哦,我的坏,修复了。
recursive_func () {
    shopt -s dotglob
    for item in $1/*; {
        fname=$(basename $item)
        [[ -L $item ]] && ((symlinks++))
        [[ ${fname::1} = '.' ]] && ((hidden++))
        [[ -d $item ]] && { ((subd++)); recursive_func "$item"; }
    }
    shopt -u dotglob
}
ls -al | wc -l