2012-09-19 46 views
0

我试图发现为什么我的遍历不起作用。我相信我已经将问题隔离到了代码中“目录包含”的地方,然后传递给了函数。该函数传递一个包含所有新文件路径的数组来回显,但由于某种原因,它只接收第一个。我错误地传递数组还是可能是其他内容?在Bash中递归广度优先遍历

#!/bin/bash 

traverse(){ 
    directory=$1 
    for x in ${directory[@]}; do 
    echo "directory contains: " ${directory[@]} 
    temp=(`ls $x`) 
    new_temp=() 
    for y in ${temp[@]}; do 
     echo $x/$y 
     new_temp=(${new_temp[@]} $x/$y) 
    done 
    done 

    ((depth--)) 

    if [ $depth -gt 0 ]; then 
    traverse $new_temp 
    fi 
} 

回答

1

您不能将数组作为参数传递。你只能传递字符串。您必须首先将数组 扩展到其内容列表。我冒昧地将depth 局限于你的函数,而不是我认为的全局变量。

traverse(){ 
    local depth=$1 
    shift 
    # Create a new array consisting of all the arguments. 
    # Get into the habit of quoting anything that 
    # might contain a space 
    for x in "[email protected]"; do 
    echo "directory contains: [email protected]" 
    new_temp=() 
    for y in "$x"/*; do 
     echo "$x/$y" 
     new_temp+=("$x/$y") 
    done 
    done 

    ((depth--)) 
    if ((depth > 0)); then 
    traverse $depth "${new_temp[@]}" 
    fi 
} 

$ dir=(a b c d) 
$ init_depth=3 
$ traverse $init_depth "${dir[@]}" 
+0

啊,谢谢你:) – Sam