使用数组通过mailx在bash中附加文件

问题描述 投票:2回答:1

我刚刚开始学习bash,正在开发我的第一个小项目。我试图使用数组作为参数来使用邮件附加文件,但是我的目录中存在一个文件邮件正在返回:没有这样的文件或目录

我尝试在via shell中手动键入命令,指定文件名而不使用数组,这样可以正常工作。

这是代码:

在我的目录中说例如我有File1,File2,File3。文件名将始终以名称“文件”开头,但每个文件的编号将有所不同。

首先,我用文件编号定义一个数组:

esend=(1 2 3)

然后我遍历数组的每次迭代并创建一个这个数组的副本,用-a [Filename]附加每次迭代

# Loop over array and build the arguments for mailx.

for i in "${esend[@]}"

do

   # for each iteration append onto array with -a [filename]

   mailarray=( "${mailarray[@]}" "-a $(find -name "File$i" | sed "s|^\./||")" )

done

每个索引中的值应为“-a File1 -a File2 -a File3”,现在我的计划是将其用作邮件的参数

# "${mailarray[@]}"  will contain the arguments ( -a File1 -a File2 -a File3 )

echo "File being sent from mail" | mailx "${mailarray[@]}" -s "Script.sh" -r "[email protected]" [email protected]

实际结果是邮件返回File1:找不到这样的文件或目录。

要么我在这里做错了,要么就是我们不能使用这种方法?

arrays bash
1个回答
0
投票

在你的情况下你需要取消引用你的数组变量mailarray,以便表示为参数,否则它在Bash中表示为一个字符串:

mailx ${mailarray[@]} -s "Script.sh" -r "[email protected]" [email protected]

但请注意,这是危险的方式,例如任何具有特殊字符的文件都无法正确处理。此外,您还没有处理find的多个输出。也没有必要删除sed的路径,而是保持更好。

我宁愿重写这样的东西(支持多个查找输出while循环,支持特殊字符-print0,退出时返回代码为mailx):

#!/bin/bash
mailargs=()
for ((i=1;i!=4;i++))
do
  while IFS= read -r -d $'\0'
  do
    mailargs+=("-a" "${REPLY}")
  done < <(find ./ -type f -name "File${i}" -print0)
done
echo "File being sent from mail"
mailx "${mailargs[@]}" -s "Script.sh" -r "[email protected]" [email protected]
exit $?

也考虑选项,例如到tar多个文件。

© www.soinside.com 2019 - 2024. All rights reserved.