What is the best way to look inside a dir开发者_开发知识库ectory and determine whether its content are directories or files. Its a homework question.
My homework requires me to write a script that counts the number of directories, files, how many are executable, writeable, and readable.
Assuming you're talking about the bourne shell family, take a look at the -d
, -x
, -w
... and I'm guessing -r
tests. Look up how a for loop works in bash to see how to iterate over the files... the general idea is
for var in directory/*; do
#stuff with $var
done
But there are some particulars relating to spaces in filenames that can make this trickier.
Use the -X style operators:
[ -d "${item}" ] && echo "${item} is a directory"
See the bash man page (search for "CONDITIONAL EXPRESSIONS") to see the complete list.
Looping through contents of a directory and counting looks like this:
dirs=0
writeable=0
for item in /path/to/directory/*; do
[ -d "${item}" ] && dirs=$(( dirs + 1 )) # works in bash
[ -w "${item}" ] && writeable=`expr ${writeable} + 1` # works in bourne shell
# Other tests
done
echo "Found ${dirs} sub-directories"
echo "Found ${writeable} writeable files"
精彩评论