Search code examples
linuxbashemailsendmail

run find command and email results


I want to use a find command in order to obtain files older than 8640 min and send the result in a email body. I used this script that makes use of a file - ATTACH_FILE - containing the results of the find command:

#!/bin/sh
ATTACH_FILE="/pub/email_attach.txt"
WORK_DIR="/pub/"
rm -f $ATTACH_FILE
find $WORK_DIR -maxdepth 1 -name '*x.rsd' -type f -daystart -mmin +8640 -exec echo {} >> $ATTACH_FILE \;

if [ ! -z $ATTACH_FILE ]; then
    FILESIZE=$(stat -c%s "$ATTACH_FILE" 2>> getLatestErr.log)
    echo $ATTACH_FILE "size $FILESIZE bytes"
    if [ $FILESIZE -gt 0 ]; then
       cat $ATTACH_FILE | mail -s "Test "$TODAY [email protected]
    fi
fi

How can I get the same result by putting a message in the body of the email without using the auxiliary file ATTACH_FILE ?


Solution

  • To expand on my comment above:

    Assign to an array variable and use printf to separate the found items with a newline character:

    #!/bin/bash
    WORK_DIR="/pub/"
    
    FILE_LIST=($(find $WORK_DIR -maxdepth 1 \
        -name '*x.rsd' -type f \
        -daystart -mmin +8640 ))
    
    if [ -n "${FILE_LIST[0]}" ]; then
       printf '%s\n' "${FILE_LIST[@]}" | mail -s "Test "$TODAY [email protected]
    fi
    

    I exchanged /bin/sh with /bin/bash, as the question is tagged with [bash].