Shell Script to recursively list files

The shell script is equivalent to “ls -R”
To show what problem may come up in such types of programs, I have taken two versions of the program. In the first version, If file names do not contain spaces or newline character, everything works well. The second version takes care of this.
First Version

#!/bin/sh 
 # Shell script to find out all the files under a directory and 
 #its subdirectories. This takes into consideration only those files
 #or directories which do not have spaces or newlines in their names 

DIR="."

function list_files()
{
 if !(test -d $1) 
 then echo $1; return;
fi

cd $1
 echo; echo `pwd`:; #Display Directory name

 for i in *
 do
 if test -d $i #if dictionary
 then 
 list_files $i #recursively list files
cd ..
 else
 echo $i; #Display File name
fi

 done
}

if [ $# -eq 0 ]
then list_files .
exit 0
fi

for i in $*
do
 DIR=$1 
 list_files $DIR
 shift 1 #To read next directory/file name
done

Second Version

#!/bin/sh 
 # Shell script to find out all the files under a directory and 
 #its subdirectories. This also takes into consideration those files
 #or directories which have spaces or newlines in their names 

DIR="."

function list_files()
{
 if !(test -d "$1") 
 then echo $1; return;
fi

cd "$1"
 echo; echo `pwd`:; #Display Directory name

 for i in *
 do
 if test -d "$i" #if dictionary
 then 
 list_files "$i" #recursively list files
cd ..
 else
 echo "$i"; #Display File name
fi

 done
}

if [ $# -eq 0 ]
then list_files .
exit 0
fi

for i in $*
do
 DIR="$1"
 list_files "$DIR"
 shift 1 #To read next directory/file name
done

As can be clearly seen from the two versions, how quoting the variables has solved the problem of dealing of file name with spaces and newline characters. Quoting is useful to give such argument easily as input to programs which now take it as a single entity instead of taking it as two or more file names because of the whitespace characters.

 

Shell Script To recursively display (list) directories

This is a shell script to recursively display only the directories

#!/bin/sh
# Shell script to find out all the directories under a directory and
#its subdirectories. This also takes into consideration those files
#or directories which have spaces or newlines in their names

DIR="."

function list_files()
{
    if !(test -d "$1")
    then echo $1; return;
    fi

    cd "$1"
    echo; echo `pwd`:; #Display Directory name
for i in *
do
  if test -d "$i" #if dictionary
  then
     echo "$i"; #Display Directory name
  fi
done

for i in *
do
   if test -d "$i" #if dictionary
   then
      list_files "$i" #recursively list files
      cd ..
  fi
done

}

if [ $# -eq 0 ]
then list_files .
exit 0
fi

for i in $*
do
    DIR="$1"
    list_files "$DIR"
    shift 1 #To read next directory/file name
done