0

I'm having a problem with my script,

it's a notifier that emails me on a specific set of time then includes a statement if the file exceeds 100kb

Here is my script, how can i configure this so that it will send me the notification?

#!/bin/bash

file="afile"
maxsize=100

while true; do

        actualsize=$(du -k "$file" | cut -f1)

        if [ $actualsize -ge $maxsize ]
        then
                echo size is over $maxsize kilobytes
                subject="size exceed on file $file"
                emailAddr="[email protected]"
                emailCmd="mail -s \"$exceedfile\" \"$emvpacifico\""
        (echo ""; echo "date: $(date)";) | eval mail -s "$exceedfile" \"[email protected]\"
                exit
        else
                echo size is under $maxsize kilobytes
        fi

        sleep 60
done
4
  • I was going to fix the formatting, but it seems I can’t edit it. Good luck! Commented Apr 9, 2018 at 21:29
  • Are the lines starting with emailCmd and (echo "" supposed to be the same logical line, or are they separate statements? Commented Apr 9, 2018 at 21:33
  • 1
    drop eval and remove the backslashes from the recipient address. Commented Apr 9, 2018 at 21:58
  • 1
    paste your code into shellcheck.net to fix the other issues. Commented Apr 9, 2018 at 21:58

1 Answer 1

1

A quick rewrite, with comments inline:

#!/bin/bash

file="afile"
maxsize=100

while true; do
   # Use `stat`, the tool for getting file metadata, rather than `du`
   # and chewing on its output.  It gives size in bytes, so divide by
   # 1024 for kilobytes.
   actualsize=$(($(stat --printf="%s" "$file")/1024))
      if [[ $actualsize -ge $maxsize ]]; then
         echo "size is over $maxsize kilobytes"
         subject="size exceed on file $file"
         emailAddr="[email protected]"
         # In almost all cases, if you are using `eval`, either
         # something has gone very wrong, or you are doing a thing in
         # a _very_ suboptimal way.
         echo "Date: $(date)" | mail -s "$subject" "$emailAddr"
      else
         echo "size is under $maxsize kilobytes"
      fi
   sleep 60
done

Also, I would suggest rather than running a script with an infinite loop, altering the script to run only once, and scheduling it to run using a cron table entry.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.