简体   繁体   中英

Attaching files using mailx command in bash script

I have 2 files in the below path that ends with.xlsx extension. One file is greater than 6 MB and the other is lesser than 6 MB.

If the file is lesser than 6 MB, I need to send an email notification with the attachment of the file. Else I need to send an email notification stating the file is greater than 6 MB and available in specified path..

#!/bin/bash
cd /opt/alb_test/alb/albt1/Source/alb/al/conversion/scr

file= ls *.xlsx -l
#for line in *.xls

min=6
actsize=$(du -m "$file" | cut -f1)
if [ $actsize -gt $min]; then
    echo "size is over $min MB and the file is available in specified path -- Need to send this content via email alone"
else
    echo "size is under $min MB, sending attachment -- Need to send the attachment"

echo | mailx -a ls *.xlsx -l test@testmail.com
fi

When I run the above script, it says -gt: unary operator expected & ls: No such file or directory

Can anyone guide how to fix this?

The -a argument can only take one filename, so you have to repeat it for each file you want to attach. You can build the attachment list in an array by looping over all the xlsx files like so:

min=6
attachments=()
for file in *.xlsx ; do
  [[ -f "${file}" ]] || continue # handles case where no xlsx files exist
  if [[ $( du -m "${file}" | cut -f1 ) -le $min ]] ; then
    attachments+=( "-a" "${file}" )
  fi
done
mailx "${attachments[@]}" -l test@testmail.com

You don't need to use ls - that's a tool for humans to look at their file system, scripts don't need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM