Create automated scan of specific directory using bash

I am trying to use bash to automate the scan of a specific directory using clamav . Having this in place is a network requirement. The below is an attempt to:

  1. count the extensions (.txt, .jpeg) in a directory and write them to a virus-scan.log (section in bold)

  2. scan each folder in the dir and log the results of the scan by date . (section in italics)

Each folder in the directory is scanned and the results of each day the scan is run is logged to /HOME/virus-scan.log by date.

Thank you :).

#!/bin/bash
DIR=/home/cmccabe/Desktop/NGS/API
line_no=$(ls | awk -F . '{print $NF}' | sort | uniq -c | awk '{print $2,$1}') # count folder type and store as variable
echo >> $HOME/virus-scan.log"The folders detected are:
$line_no"

# Get rid of old log file
rm $HOME/virus-scan.log 2> /dev/null
 
while read FILE in $DIR;
do
     # check file length is nonzero otherwise commands may be repeated
     if [ -s $FILE ]; then
          date > $HOME/virus-scan.log
          clamscan -r $FILE >> $HOME/virus-scan.log
     else "echo nothing detected by scan"
     fi
done

So... What's your question?

1 Like

Sorry, the script runs but just halts and nothing happens and I'm not sure whats wrong or if this is the best way. Thank you :).

Try for FILE in $DIR instead of while read FILE in $DIR , read actually tries to read from standard input (in this context, your keyboard).

1 Like

Thank you very much, that worked perfectly :). The explanation is appreciated :slight_smile:

Yes the for loop is best to cycle through a list.
But $DIR is only one item.
Maybe you want $DIR/* aka all items in $DIR ?
This might do what you intend

#!/bin/bash
DIR=/home/cmccabe/Desktop/NGS/API
log=$HOME/virus-scan.log

{
echo "The extensions are"
ls | awk -F'\.' 'NF>1 {ext[$NF]++} END {for (i in ext) print ext,i}'
} > $log

scanned=0
for FILE in "$DIR"/*
do
     # check file length is nonzero otherwise commands may be repeated
     if [ -s "$FILE" ]; then
          {
          date
          clamscan -r "$FILE"
          } >> $log
          ((scanned++))
     fi
done
[ $scanned -eq 0 ] && echo "nothing detected by scan" >> $log
1 Like

On linux systems clamav implements a system to watch directories using inotify subsystem.

You might want to check that out :

1 Like