1

I need a UNIX Kornshell (ksh) script that counts the number of files in directory. If the files exceed 20 files, then email results. I want the script to run every hour. I do not have access to cron. I am somewhat new to UNIX. Windows guy all my career. This is what I have so far..

#!/bin/ksh
# count.sh

while :
do
 for dir in /directory1/
 do
  echo "$dir `du $dir |wc -l`" 
 done > ./message
 mailx -s 'Dir Count' [email protected] < ./message
 sleep 3600
done

Any help is greatly appreciated.

1 Answer 1

1

The du command as shown will produce one line per directory inside the target directory, /directory1.

Your question isn't clear. It says 'if the files exceed 20 files', which I interpret as meaning 'if the number of files exceeds 20'. You're not dealing with files (as opposed to directories, FIFOs, and other types), and you don't test for "more than 20". I'm going to simplify things, and assume you mean 'if the number of names in the directory exceeds 20'.

dir=/directory1/
while :
do
    names=$(ls "$dir" | wc -l)
    if [ "$names" -gt 20 ]
    then echo "$dir $names" | mailx -s 'Dir Count' [email protected]
    fi
    sleep 3600
done
Sign up to request clarification or add additional context in comments.

4 Comments

Maybe printf "%s\n" "$dir"/* | wc -l to avoid pesky ls parsing issues?
Maybe...in general, something like that might be necessary, but it is probably not a problem here.
If the directory is big and/or load is high, you could be spending more than one hour between runs. Maybe consider a self-scheduling at job if precise timing is important.
If you use at you get into issues of knowing where your program is installed so you can arrange for it to be run again, and you need to reschedule at the top of the program to avoid time skew but it can still build up over time, but cron avoids that altogether.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.