如何用Shell脚本编写递归程序

来源: LUPA开源社区
发布时间: 2007-05-27 05:37 版权申明

字体:


文章来源于http://www.lupaworld.com

  UNIX Shell 脚本类似 DOS 的批处理命令,但比较起来 UNIX Shell 的功能更强大,在某些方面,Shell 甚至超过了一些高级语言。
  
  下边的 Shell 脚本演示了如何用 Shell 脚本编写递归程序。
  
  运行前先执行下述准备命令:
  ??ln tree.sh /usr/bin/tree
  ??ln tree.sh /usr/bin/wtree
  ??ln tree.sh /usr/bin/dtree
  ??rm tree.sh
  
  # tree.sh
  
  # Depth first Directory list
  dtree() {
  PWD=`pwd|sed 's/\/\$//`
  for d in $*
  do
  echo "${PWD}/$d"
  [ -d "$d" -a -x "$d" ] && {
  cd "$d"
  dtree *
  cd ..
  PWD=`pwd|sed 's/\/\$//` # restore PWD
  }
  done
  }
  
  # Depth first Directory list
  wtree() {
  PWD=`pwd|sed 's/\/\$//`
  for d in $*
  do
  echo ${PWD}/$d
  done
  for d in $*
  do
  [ -d "$d" -a -x "$d" ] && {
  cd $d
  wtree *
  cd ..
  }
  done
  }
  
  # Directory list
  tree() {
  PWD=`pwd|sed 's/\/\$//`
  for d in $*
  do
  echo ${PWD}/$d
  done
  }
  
  # main
  TREE=`basename $0`
  if [ "$1" ]
  then DIR="$1"
  else DIR="."
  fi
  if cd $DIR
  then $TREE *
  else echo "$0: Directory $1 read fail."
  fi
  
  # (End)
文章来源于http://www.lupaworld.com

声明:LUPA开源社区刊登此文只为传递信息,并不表示赞同或者反对。

查看全部评论(0)我来说两句 直接向LUPA提出您的宝贵建议

-5 -3 -1 - +1 +3 +5