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.

 

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s