There's no good way of doing this without an array. (There's a not good way of doing it, using eval
, but the array is simpler.)
The problem is that you want each file to end up as one argument to email
, but you want to accumulate all those arguments into a Bash variable. There's just no way to do that: you can cause the Bash variable to be inserted as a single argument ("$arg"
) or you can cause it to be inserted as however many words it gets split into ($arg
), but you can't get it to be split according to whether or not spaces were escaped when the variable was created, because Bash only remembers the string assigned to a variable, not the escape marks.
However, you can do it with an array, because you can make every filename exactly one array element, and you can get Bash to insert an array as one argument per element.
Here's how:
# File paths
destinationPath="/cygdrive/c/Documents and Settings/Eric/My Documents/"
attachments="\n2013-12-12.pdf"
body="Test Body"
recipient="asdf@asdf.com"
# Prepare attachments
args=()
for file in $attachments ; do
file=${file//[ \\n]/}
touch $file
mv $file "$destinationPath/$file"
args+=(-a "$destinationPath/$file")
done
# Send email
echo -e $body |
email --from-addr nosender@mydomain.com \
--from-name "Automated CSS Downloader" \
--subject "Downloaded new file(s) from CSS" \
"${args[@]}" eric@mydomain.com
You might also want to make the attachments
variable into an array; from the presence of the newline character, I'm assuming that you're actually setting it in some more complicated way, so I didn't change the code. But your current code won't work if the attachment name has a space in it (and I'm pretty sure that the newline will be eliminated by the parameter expansion in the for
form, unless you've altered the value of $IFS
, so file=${file//[ \\n]/}
shouldn't be necessary.)