1

I am trying to analyze the files/directories inside of a directory using a shell script, for example if the file is readable, if it is a file, if it is a directory, etc. My script is set up to take a directory as input. so I would type 'file.sh directoryname'. However, when I create a for loop to analyze the files, it analyzes the files in my current working directory rather than the specified directory name.

This is my broken code:

file=$1
set mypath = $file
for file in $mypath *
do

if [ -d $file ]
  dirCount=`expr $dirCount + 1`
fi

done

Why does this read the working directory instead of the specified directory? Any help is appreciated. Thanks

2
  • Alternatively, you could always do this: find dirname -type f -maxdepth 1 Commented Apr 24, 2010 at 0:15
  • Drop the -maxdepth 1 for a recursive count Commented Apr 24, 2010 at 0:16

3 Answers 3

1

I think you have an error here:

set mypath = $file

Just do

mypath = $file

and that should work out just fine.

Sign up to request clarification or add additional context in comments.

Comments

1
# check this one     
file=$1
mypath=$file
dirCount=0
#ls $file
for file in `ls $mypath`
do
file=./$mypath/$file
#a=`ls -l $file`
echo $a
if [ -d $file ]
then
  dirCount=`expr $dirCount + 1` #increment count
        echo $dirCount
fi
done

#if count value is grater than 1 then only print value
if [ $dirCount -ne 0 ]
then
echo -e "\ncount is $dirCount    $$"
fi

Comments

0

you can try this. but the script will go into issue when the folder name have blank space.

#/bin/bash
path=$1
for file in $path/*
do
if [ -d $file ];then
  dirCount=`expr $dirCount + 1`
fi
done
echo $dirCount

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.