【发布时间】:2019-11-24 14:19:57
【问题描述】:
我正在尝试在 bash 中实现一个函数,该函数显示给定深度的文件/目录树。它需要 3 个参数。
$1 = *current directory*
$2 = *current depth*
$3 = *lines*
例如,如果我的当前目录是“.../living/”,我的深度是2,我的函数应该输出:
DIR .../living/
----DIR animals
--------FILE dog
--------FILE cat
----DIR plants
--------FILE flowers
如您所见,每更改一次深度,行数就会增加 4 行。文件的类型(DIR,FILE)不是这个线程的问题。 到目前为止,这是我所拥有的:
function tree {
#some code to get the directory in variable cwd
...
a=$(getType $cwd)
echo "$a $cwd"
depth=3 #the value does not matter, it's just for you guys to see
drawTree $cwd $depth "----"
}
function drawTree {
if [[ $2 == 0 ]]; then
return
fi
dat=$1
list=$(ls $dat)
depth=$2
lines=$3
for d in $list; do
f="$dat/$d"
t=$(getType $f)
echo "$lines$t $d"
if [[ $t == "DIR" ]]; then
g=$(($depth-1))
l="$lines----"
if [[ $g > 00 ]]; then
drawTree $f $g $l
fi
fi
done
这段代码的输出很遗憾是错误的,我不知道为什么。
【问题讨论】:
-
引用你的变量,“$var_whatever”,使用数组来避免一些问题,...太多的事情要修复——抱歉。推荐阅读:tldp.org/LDP/Bash-Beginners-Guide/html
-
我倾向于不同意建议将 ABS 作为参考——从它的建议中过滤不良做法并不需要特别小心。 shellcheck.net、mywiki.wooledge.org/BashPitfalls、mywiki.wooledge.org/BashGuide 和 mywiki.wooledge.org/BashFAQ 可能是更好的起点。