Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57124
  • 博文数量: 17
  • 博客积分: 720
  • 博客等级: 军士长
  • 技术积分: 155
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-21 13:34
文章分类

全部博文(17)

文章存档

2011年(1)

2009年(1)

2008年(5)

2007年(6)

2006年(4)

我的朋友
最近访客

分类:

2006-04-13 18:49:40

花了一下午的时间,写出这个脚本,希望大家能用的上。  主要功能如下:
1. 显示树形目录结构。本示例中最大显示8级目录(通过level变量控制)
2. 如果目录为空,则在目录名后附加“/”以区别于普通文件
3. 不支持隐藏文件
 
设脚本名称为:list,源代码如下:
#!/bin/bash
recdir ()            #定义函数recdir,递归处理目录
{
    level=$(($level+1))
    if [ $level -gt 8 ];then   #如果目录级数大于8,则不处理
       level=$(($level-1))
       return 1
    fi
    for file in "$@"; do
        thisfile=$thisfile/$file
         #如果目录为空 
        if [ -d "$thisfile" ] && [ "$(ls $thisfile)" = "" ]; then
           if [ "$level" -gt 2 ];then
              count=$(($level-2))
              while [ $count -gt 0 ]
              do
                 echo -ne $shuxian$tab
                 count=$(($count-1))
              done
           fi
           echo -n $shuxian$dash
           echo ${file}/
        elif [ -d "$thisfile" ];then     #如果目录不为空
            if [ "$level" -gt 2 ];then
              count=$(($level-2))
              while [ $count -gt 0 ]
              do
                   echo -ne $shuxian$tab
                   count=$(($count-1))
              done
            fi
            echo -n $shuxian$dash
            echo $file
            recdir $(command ls $thisfile)
        else                              #如果是文件
            if [ "$level" -gt 2 ];then
               count=$(($level-2))
               while [ $count -gt 0 ]
               do
                   echo -ne $shuxian$tab
                   count=$(($count-1))
               done
            fi
            echo -n $shuxian$dash
            echo $file
        fi
        thisfile=${thisfile%/*}

    done
 
    level=$(($level-1))
}
 
#以下为主程序
 
tab="\t"      #定义变量tab,用于输出TAB字符                
shuxian="|"  
dash="-------"
level=1       #定义用户给定的目录为1级,并以此为基准展开
for tryfile in "$@"; do
        if [ -d "$tryfile" ] && [ "$(ls $tryfile)" = "" ]; then
           echo ${tryfile}/
        elif [ -d "$tryfile" ];then
            echo $tryfile
            thisfile=$tryfile
            recdir $(command ls $tryfile)
        else
            echo $tryfile
        fi
        echo
done
unset tab shuxian dash level count
exit 0

程序运行结果如下:
./list /tmp
/tmp
|-------a
|-------data
|       |-------abc/
|       |-------data.tar.bz
|       |-------nfdldate
|       |-------nfdldate.bak
|       |-------nfList.xxx
|       |-------nfurl
|       |-------nfurl.bak
|-------dir2
|       |-------dir3
|       |       |-------dir4
|       |       |       |-------dir5
|       |       |       |       |-------dir6
|       |       |       |       |       |-------7
|       |       |       |       |       |       |-------8
|       |       |       |-------same5/
 
ps:如发现bug,请与我联系。我会尽快修复。  谢谢!
阅读(1126) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~