Basic unix script to count files of various permissions

I have a project due in a few hours to count how many files and subdirectories are in a directory and to count the number of readable, writable, and executable items. I have this code so far, but my counters always return zero. Please help me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/bash

r=0
w=0
x=0
f=0
d=0

if [ "$1" = "" ] ; then
 echo "Usage: homework4.sh <direcotry_name>"
elif [ ! -d  "$1" ] ; then
 echo "$1 : no such directory"
else
 for files in `ls -1  ~/$1`
  do
    [ -r "${files}" ] && r=`expr $r + 1` #experimenting with diff technique here

    if [ -x $files ] ; then
    $x = `expr $x + 1`
    fi

    if [ -w $files ] ; then
     w = `expr $w + 1`
    fi

    if [ -d $files ] ; then
     d = `expr $d + 1`
    fi

    if [ -f $files ] ; then
     f = `expr $f + 1`
     fi

 done

echo "Number of files : $f "
echo "Number of directories : $d "
echo "Number of readable items : $r "
echo "Number of executable items : $x "
echo "Number of writeable items : $w "
fi
exit
I would use ls -AlR to get the files with attributes. You can use grep or egrep to parse the output for flags and wc -l to count the number of lines in the output.

And there's the option of running multiple times for each case or storing the full list in a temp file.

Good luck.
Last edited on
Topic archived. No new replies allowed.