dubya
dubya

Reputation: 25

Reading into directory, unix shell script

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

Upvotes: 1

Views: 2148

Answers (3)

Sylar
Sylar

Reputation: 1

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

Upvotes: 0

vishal
vishal

Reputation: 11

# 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

Upvotes: 1

Jonathan Holloway
Jonathan Holloway

Reputation: 63672

I think you have an error here:

set mypath = $file

Just do

mypath = $file

and that should work out just fine.

Upvotes: 1

Related Questions