Counting the number of readable, writable, and executable items in a directory

Hello, I'm writing a script in sh in which the first command line argument is a directory. from that, i'm suppose to count the number of readable, writable, and executable items in the directory. I know using $1 represents the directory, and ls would display all the items in the directory, and that ls | wc -l would count the number of items. I'm uncertain as to how to filter ls so that only the readable/writable/executable files are shown and counted, and since I don't know if i'm the user, group, or other I cant check the permissions.

could someone show me how to do this? Thanks

USER=`whoami`
for GROUP in `groups`
do
  GROUPLIST=${GROUPLIST}\\\|${GROUP}
done
READ=0
WRITE=0
EXEC=0
for FILE in `ls`
do
  if ls -l $FILE | grep $USER
  then
    if ls -l $FILE | cut -c2 | grep r
    then
     READ=`expr $READ + 1`
    fi
  elif ls -l $FILE | egrep $GROUPLIST
  then
 
  else
  fi
done
 

You will have to fill in the gaps and add code for all conditions but you should get the idea. Someone else might know an easier way.

This sounds like homework. We have a homework forum.

Anyway, please post homework there. The answer I'm giving you will not be believed by your prof - i.e., she will think you got it off the internet, which is true.

ls -l $1 | awk ' $1 ~ /r/ {r++} $1 ~ /w/ {w++} $1 ~ /x/ {x++} 0 
                    END { printf( "read %d write %d execute %d \n", r,w,x) }' 

Which approach you take depends on whether or not the script counts what the user that ran the script can do, or a more general approach.

@jim mcnamara, whats the 0 for after the {x++}?

Hint: Have a look at the -r -w and -x options of test.

1 Like