2014-11-23 18 views
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 

這段代碼的輸出是可悲的是假的,我不知道爲什麼。

+0

引用您的變量,「$ var_whatever」,使用陣列才能避免一些問題,......太多的事情來解決 - - 對不起。建議閱讀:http://www.tldp.org/LDP/Bash-Beginners-Guide/html/ – ajaaskel 2014-11-23 15:07:07

+0

http://tldp.org/LDP/abs/html/ – ajaaskel 2014-11-23 15:23:33

+0

我傾向於不同意將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

回答

0

該代碼有相當多的問題。

最嚴重的是你的變量不是本地的(見help local),這在遞歸函數中可能是災難性的。在drawtree的循環中,第二次迭代將會看到對$depth$lines的不需要的修改,這兩者都會導致輸出以不同的方式出現錯誤。

另外:

g=$(($depth-1)) 
l="$lines----" 
if [[ $g > 00 ]]; then 
    drawTree $f $g $l 
fi 

會更好,而不那麼多不必要的變數使用運算,而不是字符串比較的書面和:

if ((depth > 1)); then 
    drawTree $f $((depth - 1)) ${lines}---- 
fi 

最後:

list=$(ls $dat) 
for d in $list; do 

將失敗如果在文件路徑中存在空格或shell元字符,則會造成災難性的後果。更好的是使用bash的陣列和水珠擴張而非ls命令):

# Create an array from a glob 
list=("$dat"/*) 
# Use the elements of the array, individually quoted: 
for d in "${list[@]}"; do