Advertisement

recursive shell script

Started by September 27, 2004 06:25 PM
0 comments, last by mrhollow 19 years, 11 months ago
I'm writing a bash shell script for a project and basically what it's supposed to do is tell me the number of directories, number of regular files and total file sizes for all regular files starting at a directory which is passed to the script as a parameter. Well I have it working fine if the script is ran in the directory I wish to start at but once I try to have it take as a parameter the starting directory and go from there it fails. I'm not really sure how to get this part to work. Here is my script thus far: #! /bin/bash d=0 f=0 sz=0 function recurs () { local i for i in $(ls $1) do if [ -d $i ] then d=`expr $d + 1` pushd $i > /dev/null recurs $i popd > /dev/null else f=`expr $f + 1` sz=`expr $sz + $(stat $i -c %s)` fi done } recurs echo "num dirs = $d" echo "num files = $f" echo "total file size = $sz" It's like it's not trying to start where I tell it as a parameter and throwing up stat and expr errors. Thanks. -SirKnight
There are other ways, but the simplest thing I can think of would be to cd to the directory in question at the top of the script, i.e.:

#! /bin/bash

d=0
f=0
sz=0

function recurs ()
{

cd $1

local i
for i in $(ls $1)
do
if [ -d $i ]
then
d=`expr $d + 1`
pushd $i > /dev/null
recurs $i
popd > /dev/null
else
f=`expr $f + 1`
sz=`expr $sz + $(stat $i -c %s)`
fi
done
}

recurs

echo "num dirs = $d"
echo "num files = $f"
echo "total file size = $sz"

This topic is closed to new replies.

Advertisement