bash list dir tree, tree in bash

从某个人的博客里参考的文章,然后改动成和tree命令一样的显示, 

但是运行非常慢,不知道怎样查看那块儿代码运行效率有问题,希望有人指正

#! /bin/bash


print_dir(){
        local not_last_dir=$3
        local replaced_prefix=""
        if [[ $not_last_dir -eq 1  ]]; then
            replaced_prefix=`echo -n $2 |sed 's/+/ /g' | sed 's/...$/|-/g'`
        else
            replaced_prefix=`echo -n $2 |sed 's/+/ /g' | sed 's/...$/\`-/g'`
        fi




        printf "%s$replaced_prefix"
        #printf "%s   "
        has_space=" "
        if [[ $2 == "" ]]; then
           has_space="" 
        fi
        if [ -L $1 ];then
            echo "${has_space}${1##*/} -> $(readlink -n -f $1)"
        else
            echo "${has_space}${1##*/}"
        fi
}
list_dir(){


        print_dir $@ 
        if [ -d $1 ] && [ ! -L $1  ]
        then
                local total_num=$(ls -1A $1 |wc -l)
                local num=0 
                local not_last_dir=1


                for sub_dir in $(ls -1A $1); do
                        local  prefix_string="$2"
                        #echo in:$prefix_string
                        let num=num+1
                        if [[ $num -lt $total_num ]];then
                            not_last_dir=1
                        else
                            not_last_dir=0
                        fi
                        if [[ $not_last_dir -eq 1 ]]; then
                            prefix_string="$prefix_string|++"
                        else
                            prefix_string="$prefix_string+++"
                        fi
                        #echo "$total_num, $num, $not_last_dir,[$prefix_string]"
                        list_dir $1/$sub_dir $prefix_string $not_last_dir
                        # remove added prefix after printed
                        prefix_string=$(echo -n $prefix_string | sed 's/...$//g')
                        #echo out:$prefix_string
                done
        fi
}
list_directory(){
        local prefix_string=""
        list_dir $1 $prefix_string
}


if [ "$#" != "1" ];then
        echo "Usage: ./make_dir_tree.sh dir"
        exit 1
fi
#ls $1 >/dev/null 2>&1
if [ ! ls $1 >/dev/null 2>&1 ]
then
        echo "This is not a valid directory or file!"
        exit 1
fi


dir=`echo -n $1 |sed 's/\/$//g'`
list_directory $dir
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值