开发者

Looping through content of the current directory

开发者 https://www.devze.com 2023-01-28 07:17 出处:网络
What is the best way to look inside a dir开发者_开发知识库ectory and determine whether its content are directories or files. Its a homework question.

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消