現在のディレクトリのツリー構造を印刷するためのシェルスクリプトエラー

現在のディレクトリのツリー構造を印刷するためのシェルスクリプトエラー

私は次のスクリプトを書いた。

  #!/bin/bash

if [ $# -eq 0 ]
then
    read current_dir
else
    current_dir=$1
fi

function print_tree_representation ()
{
    for file in `ls -A $1`
    do
        local times_p=$2
        while [ $times_p -gt 0 ]
        do
            echo -n "----"
            times_p=$(( $times_p - 1 ))
        done
        echo $file

        if test -d $file
        then
            local new_path=$1/$file
            local new_depth=$(( $2 + 1 ))

            print_tree_representation $new_path $new_depth        
        fi
    done
}

print_tree_representation $current_dir 0

引数として渡されたディレクトリのツリー構造を印刷するために使用されます。しかし、2番目の深さから抜け出すことはありません。私は何が間違っているのかわかりません。

ベストアンサー1

問題は次の行にあります。

if test -d $file

$file抽出したコンテンツにはls -Aフルパスは含まれません。行を次に置き換えると問題を解決できます。

if test -d "$1/$file"

別のバグがあります。ファイル名にスペースが含まれている場合は、どこでも発生します。ファイル名を引用符で囲みます。

おすすめ記事