linux - Bash中的递归广度优先遍历

标签 linux bash recursion tree breadth-first-search

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

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

最佳答案

您不能将数组作为参数传递。您只能传递字符串。你必须扩大 数组首先是其内容的列表。我冒昧地制作了 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[@]}"  

关于linux - Bash中的递归广度优先遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12503958/

相关文章:

linux - 不满足在 Beaglebone 上按下按钮的 GIOCondition G_IO_PRI

linux - 如何在 bash 脚本中递归地执行 foreach *.mp3 文件?

linux - 打开本地文件需要注意什么?

用于文件夹列表的 Python Inotify

linux - 在文件名中调用时 Shell 变量为空,但在回显或在其他地方调用时则不是

用于 Linux 的 mysql 命令行客户端

linux - 如何将文件从 Linux 实例正确复制到 aws ec2 实例?

haskell - 我们如何限制 Haskell 中的递归调用?

javascript - 在javascript中遍历递归关系矩阵

java - 如何打印二叉树中节点数最多的级别?