Chinaunix首页 | 论坛 | 博客
  • 博客访问: 106988
  • 博文数量: 19
  • 博客积分: 471
  • 博客等级: 下士
  • 技术积分: 251
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-16 10:03
文章分类

全部博文(19)

文章存档

2013年(1)

2012年(5)

2011年(13)

分类: LINUX

2012-11-30 23:49:58

中文第2版第5章流程控制 Page 157
以下2个函数,recls调用递归函数recdir实现简单的tree功能
recdir ()
{
    tab=$tab$singletab

  for file in "$@"; do
    echo -e $tab$file
    dir=$dir/$file
    if [ -d $dir ]; then
      recdir $(command ls $dir)
    fi
    dir=${dir%/*}
  done
  tab=${tab%\\t}
}


recls ()
{

    singletab="\t"
    for tryfile in "$@"; do
    echo $tryfile
    if [ -d $tryfile ]; then
      dir=$tryfile
      recdir $(command ls $tryfile)
    fi
    done
    unset dir singletab tab
}
实现效果如下:
# recls /boot
/boot
    config-2.6.18-164.el5
    grub
        device.map
        e2fs_stage1_5
        fat_stage1_5
        ffs_stage1_5
        grub.conf
        iso9660_stage1_5
        jfs_stage1_5
        menu.lst
        minix_stage1_5
        reiserfs_stage1_5
        splash.xpm.gz
        stage1
        stage2
        ufs2_stage1_5
        vstafs_stage1_5
        xfs_stage1_5
    initrd-2.6.18-164.el5.img
    message
    symvers-2.6.18-164.el5.gz
    System.map-2.6.18-164.el5
    vmlinuz-2.6.18-164.el5
要求修改代码的功能,以提高其输出能力,如下:
1. 判断是否是文件或目录,改变输出结果,使每个目录名在显示时后面附加符号/。
2. 修改代码使其最多向下循环8个子目录(即最大不超过屏幕的最右边)。
   提示:考虑TAB的实现过程。
3. 改变输出使其包含短线划线并在每个目录后面加入空行,这样,
./
|-------ascript
|-------bash2examples.tar.gz
|-------bashdb
|-------bashdb.pre
|-------bash.tar.Z
|-------debugger/
|    |
|    |-------bashdb
|    |-------bashdb.fns
|    |-------bashdb.pre
|-------examples/
|    |
|    |-------chapter4/
|    |    |
|    |    |-------albums
|    |    |-------ascript

完成如下:
:

recdir ()
{
    tab=$tab$singletab

  for file in "$@"; do
    cnt=$#
    dir=$dir/$file
    if [ -d $dir ]; then
      echo -e ${tab/%\\t/$bar}$file/ # TAB替换为横杠
      if [ "`ls $dir|wc -l`" -ne 0 ]; then
          echo -e $tab$stick # 非空目录才有分支的竖杆
      fi
      recdir $(command ls $dir)
    else
      echo -e ${tab/%\\t/$bar}$file
    fi
    dir=${dir%/*}
  done
  tab=${tab%|\\t}
}


recls ()
{

    singletab="|\t"
    stick="|"
    bar="-------"
    for tryfile in "$@"; do
    if [ -d $tryfile ]; then
      echo $tryfile/
      dir=$tryfile
      recdir $(command ls $tryfile)
    else
      echo $tryfile
    fi
    done
    unset dir singletab stick bar  tab
}

第2个问题未完成,主要问题在于要找到屏幕宽度的像素。
阅读(1760) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~