【问题标题】:Recursive breadth first traversal in BashBash中的递归广度优先遍历
【发布时间】:2012-09-20 07:01:51
【问题描述】:

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

#!/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
}

【问题讨论】:

    标签: linux bash recursion tree breadth-first-search


    【解决方案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 "$@"; do
        echo "directory contains: $@"
        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[@]}"  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2016-02-15
      • 2019-08-10
      • 1970-01-01
      相关资源
      最近更新 更多