Tuesday, February 27, 2007

Spider the directories

I was thinking of how to spider the directories in unix and list all its subdirectory tree and files as in `find` command. Here goes a simple script for it.




#!/bin/bash
# `find path` implementation
# usage: basname($0) path

lsdir(){

local dirs; # `local` modifier prevents getting the values from inner calls.
dirs=$1;
# IFS="
#"; # prevents space separated filenames as separate items.
# IFS is set to newline, better solution welcome
IFS=$'\n'; # Better solution
for i in $(ls --sort=n -a $dirs); do

if [ \( "$i" = "." \) -o \( "$i" = ".." \) ]; then
continue;
fi

newfpath=${dirs}/${i};
echo $newfpath;

if [ -d $newfpath ]; then
lsdir $newfpath; # recursive call
fi
done;
}

dirpath=$1;
echo $dirpath;
dirpath=${dirpath%*/}; # strip the given trailing slash from pathname end.

lsdir $dirpath;

No comments: