0

トラバーサルが機能しない理由を見つけようとしています。「ディレクトリに含まれる」と書かれているコードのポイントまで問題を切り分け、次に関数に渡されたものを特定したと思います。関数には、エコーするすべての新しいファイル パスを含む配列が渡されますが、何らかの理由で最初のものしか受信していません。配列を間違って渡していますか、それとも何か他のものでしょうか?

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

1 に答える 1

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[@]}"  
于 2012-09-19T22:54:02.370 に答える