Search code examples
bashshellsh

Bash shell script to get email When New file comes Without Inotify


Is there any why to create Bash shell script which send all new incoming file information ( filename; arriving date/time; filesize) into certain folder.

i can not use inotify so please do not consider it as option.


Solution

  • Something like:

    #!/bin/bash
    
    monitor_dir=/path/to/dir
    [email protected]
    
    files=$(find "$monitor_dir" -maxdepth 1 | sort)
    IFS=$'\n'
    
    while true
    do
      sleep 5s
    
      newfiles=$(find "$monitor_dir" -maxdepth 1 | sort)
      added=$(comm -13 <(echo "$files") <(echo "$newfiles"))
    
      [ "$added" != "" ] &&
        find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
        mail -s "incoming" "$email"
    
      files="$newfiles"
    done
    

    This should work well as long as there are no files created containing newlines in their names. Other caveats are that I can't see any option for find to output a human readable size, so getting that would require further processing. Also most filesystems don't actually store file creation time, modification time is used instead (not that it makes any real difference in this case).

    Update

    To test the script and have it print to a terminal just remove the mail line and the pipe (|) at the end of the previous line. I changed the monitor directory to a variable at the top rather than just directly coded, so fill in the directory here. Then put the script into a file, set executable permissions and run (./filename when in the scripts directory). If you put files into your directory, they should appear on the script's console after a few seconds.

    To send emails, you need to make sure your system is set up to send emails from the command line. Your distro should have instructions for that. You can send a test email with:

    <<<hello mail -s "test email" [email protected]
    

    If you don't want to set up for sending emails, it is also possible to email a local system user at username@localhost. You can check this with the mail command or it is possible to set up a different mail reader like Thunderbird.