1
我想在bash中實現一個函數,它顯示給定深度的文件/目錄樹。它需要3個參數。在Bash的樹hiearchy
$1 = *current directory*
$2 = *current depth*
$3 = *lines*
例如,如果我的當前目錄是「... /生活/」我的深度爲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」,使用陣列才能避免一些問題,......太多的事情來解決 - - 對不起。建議閱讀:http://www.tldp.org/LDP/Bash-Beginners-Guide/html/ – ajaaskel 2014-11-23 15:07:07
http://tldp.org/LDP/abs/html/ – ajaaskel 2014-11-23 15:23:33
我傾向於不同意將ABS作爲參考 - 它並不特別注意從其建議中篩選出不良做法。 http://shellcheck.net/,http://mywiki.wooledge.org/BashPitfalls,http://mywiki.wooledge.org/BashGuide和http://mywiki.wooledge.org/BashFAQ可能是更好的起點。 – 2014-11-24 00:34:02