【问题标题】:Attaching files using mailx command in bash script在 bash 脚本中使用 mailx 命令附加文件
【发布时间】:2022-12-16 09:35:59
【问题描述】:

我在以下路径中有 2 个以 .xlsx 扩展名结尾的文件。一个文件大于 6 MB,另一个文件小于 6 MB。

如果文件小于 6 MB,我需要发送带有文件附件的电子邮件通知。否则我需要发送电子邮件通知 说明文件大于 6 MB 并且在指定路径中可用..

#!/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

当我运行上面的脚本时,它说 -gt: unary operator expected & ls: No such file or directory

谁能指导如何解决这个问题?

【问题讨论】:

  • file= ls *.xlsx -l你测试了吗? shellcheck.net
  • 它列出了 2 个以 .xlsx 扩展名结尾的文件。如果只有一个文件,则脚本运行良好。
  • 它与问题没有直接关系,但是这个脚本有几个语法错误,shellcheck 可以帮助您解决。您应该将它粘贴到那里并尝试修复它的发现。
  • 例如:unary operator expected是因为$actsize可能是空的,因为$file是空的。 file= ls *.xlsx -l 没有给file 分配任何东西,它只是运行ls 命令并在终端上显示输出。

标签: linux bash shell unix


【解决方案1】:

-a 参数只能使用一个文件名,因此您必须为每个要附加的文件重复该参数。您可以通过遍历所有 xlsx 文件来在数组中构建附件列表,如下所示:

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

您不需要使用 ls - 这是人类查看其文件系统的工具,脚本不需要它。

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多