从某个人的博客里参考的文章,然后改动成和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