1

I'm trying to send a log file every 24 hours or so via email. Currently I am using mutt for this. You can call mutt like this:

mutt -s "Log" -a file_attachment [email protected] 

I know I can list the most recently created files using find and mtime but I want to be able to define a bash function that will find the most recently created file in a directory and then send it as an email attachment.

How can I accomplish this?

2 Answers 2

3

With zsh:

mutt -s "Log" -a /path/to/*.log(.om[1]) [email protected]

That uses zsh glob qualifiers. While other shell globs can only generate filenames based on their name, in zsh, you can use those qualifiers ((.om[1]) above), to select based on file attributes (type, size, times, permissions...) or other criteria of your own, affect the order, apply various transformations, or select a range.

In this case we use these qualifiers:

  • .: select only regular files.
  • om: order by modification time (newest first)
  • [1]: select only the first one.

Note that if there are no log files in /path/to, the glob will fail and the command will be aborted (as you'd expect, but other shells work differently).

GNUly, the equivalent would be something like:

latest=$(
  find /path/to -maxdepth 1 -name '*.log' -printf '%T@:%p\0' |
    sort -rzg | sed -z 's/^[^:]*://;q'
)
[ -n "$latest" ] &&
  mutt -s "Log" -a "$latest" [email protected]
1
  • Could you please expand on (.om[1])?
    – jasonwryan
    Aug 7, 2014 at 7:08
1
Get_Attachment_Name ()
{
   file_attachment_dir="Whatever you want your directory to be"
   file_attachment=`ls -lrt -- "$file_attachment_dir" | grep -v "^[bcdl]"| tail -n 1 | awk '{print $9}'`
}

Grepping out any output lines starting with b, c, d, or l will eliminate trying to send block special files, character special files, directories or symbolic links.

man ls to see other file types that you may wish to exclude from your output.

2
  • Why not include only regular files grep '^-' instead of excluding the ones you don't want? Aug 7, 2014 at 8:44
  • Note that it assumes file and user names don't contain newline or blank characters (and symlink targets don't contain newline characters). Using the -n option to ls to list users with their uid would improve matters slightly. You may want to fix the locale to C to make sure the date field always has 3 fields as well. Aug 7, 2014 at 8:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .