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