树形显示目录

一、编写shell脚本

#!/bin/bash 
function main(){  
    local pre=$1
    local name=$2
    echo "$pre$name"
    test -d "$name" && test -r "$name" && test -x "$name" && test ${name:0:1} != "-" || return 0
    cd "$name" 
    pre=${pre//├/│}
    pre=${pre//[─└]/ }
    local cnt=` ls -la | wc -l`
    find -maxdepth 1 |
    while read i ;do
        cnt=$((cnt-1));
        test "$i" = '.' &&  continue
        i=${i:2}
        test $cnt -gt 2 && main  "$pre├─" "$i" || main "$pre└─"  "$i" 
    done 
    cd ..
    return 0
} 
root=`pwd`
cd ..
main ''  "${root##*/}"

如果一个文件夹名字叫-23 或这叫-xxx ,系统cd时就会对它进行转义,所以就会出错.
解决方法是 ls -l -- -2334,这里的--表示选项结束.ls 就会把-2334理解成字符串而不是选项.
或者文件夹名为若干个空格,也会出错.可是我的Ubuntu上竟然允许这么做,也没有对文件名进行审查.本程序进行了-xx审查.

二、编写Python脚本

import os
import sys

root=sys.argv[1] if len(sys.argv)>1 else os.curdir

def go(root,pre,depth):
    a=os.listdir(root)
    p=pre.replace("-"," ").replace("`"," ")
    for ind,i in enumerate(a):
        if ind==len(a)-1:
            prefix="`-"
        else:
            prefix="|-"
        if os.path.isdir(os.path.join(root,i)):
            print(p+prefix+i)
            go(os.path.join(root,i),p+prefix,depth+1)
        else:
            print(p+prefix+i)
go(root,"",0)

三、一句话shell

1、我们可以使用find命令模拟出tree命令的效果,如显示当前目录的 tree 的命令:

$ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'

2、你也可以写一个别名来快速执行该命令,运行如下命令,将上面这个命令写到~/.bash_profile里,以后直接运行tree命令就更方便了:

$ alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"

四、有现成的库

如果是Ubuntu,sudo apt-get install tree
如果是mac,brew install tree(brew命令需要安装)

原文地址:https://www.cnblogs.com/weiyinfu/p/8607425.html