シェルスクリプトでディレクトリをツリー表示

2010-07-11追記
id:thincaさんからtreeコマンドを教えてもらったので、そちらを使えばOKです。
ここで紹介しているのは車輪の最発明ということで。(Bashの勉強にはなるかも)
UNIXの部屋 コマンド検索:tree (*BSD/Linux)

仕事ではよくシェルスクリプト(Bash)を使用します。シェルスクリプトといえでも結構色々できるんですよね。テキスト処理とかはsed , cut , grepなどなど色々便利なコマンドがあるので、だいたいのことはできます。


そこでディレクトリをツリー表示できるスクリプトを作ってみました。視覚的にディレクト構成を見たいときがたまーにあるので。

  • dir_tree.sh
#!/bin/bash
#{{{function dir_tree()
function dir_tree()
{
  local dir=$1
  local indent="$2  "
  local head
  local next
  local list="$(find $dir -maxdepth 1 | sed 1d)"
  local num=$(echo "$list" | wc -w)
  local count=0
  local name

  for file in $list
  do
    ((count++))
    if [ $count -eq $num ]
    then
      head="$indent└─"
      next="$indent "
    else
      head="$indent├─"
      next="$indent"
    fi

    name=$(basename $file)
    echo "$head$name"
    [ -d "$dir/$name" -a ! -L "$dir/$name" ] && dir_tree $dir/$name "$next"
  done
  
}
#}}}

top=$1

echo $(basename $top)
dir_tree $top


ためしにRailsの初期ディレクトリをツリー表示してみると、こんな感じ。
./dir_tree.sh ~/work/sample

sample
  ├─public
  │  ├─422.html
  │  ├─favicon.ico
  │  ├─images
  │  │  └─rails.png
  │  ├─index.html
  │  ├─robots.txt
  │  ├─500.html
  │  ├─404.html
  │  ├─stylesheets
  │  └─javascripts
  │     ├─application.js
  │     ├─controls.js
  │     ├─effects.js
  │     ├─dragdrop.js
  │     └─prototype.js
  ├─tmp
  │  ├─cache
  │  ├─sockets
  │  ├─pids
  │  └─sessions
  ├─script
  │  ├─about
  │  ├─generate
  │  ├─destroy
  │  ├─server
  │  ├─runner
  │  ├─console
  │  ├─plugin
  │  ├─dbconsole
  │  └─performance
  │     ├─profiler
  │     └─benchmarker
  ├─app
  │  ├─views
  │  │  └─layouts
  │  ├─controllers
  │  │  └─application_controller.rb
  │  ├─models
  │  └─helpers
  │     └─application_helper.rb
  ├─db
  │  └─seeds.rb
  ├─config
  │  ├─boot.rb
  │  ├─database.yml
  │  ├─locales
  │  │  └─en.yml
  │  ├─environments
  │  │  ├─development.rb
  │  │  ├─test.rb
  │  │  └─production.rb
  │  ├─routes.rb
  │  ├─initializers
  │  │  ├─session_store.rb
  │  │  ├─cookie_verification_secret.rb
  │  │  ├─mime_types.rb
  │  │  ├─inflections.rb
  │  │  ├─backtrace_silencers.rb
  │  │  └─new_rails_defaults.rb
  │  └─environment.rb
  ├─Rakefile
  ├─lib
  │  └─tasks
  ├─vendor
  │  └─plugins
  ├─log
  │  ├─development.log
  │  ├─test.log
  │  ├─production.log
  │  └─server.log
  ├─test
  │  ├─functional
  │  ├─test_helper.rb
  │  ├─fixtures
  │  ├─integration
  │  ├─performance
  │  │  └─browsing_test.rb
  │  └─unit
  ├─doc
  │  └─README_FOR_APP
  └─README


Ubuntu10.04のBashで確認しました。Macやzshで動くかはわかりません。