1

I'm getting stuck on something that surely has a simple solution. I'm using mail from GNU mailutils to periodically send a log file to relevant people.

mail -s "The Subject" someone@example.com <<< "Message body"

Now I want to incorporate that in a script that performs a bunch of tasks, but I'm getting stuck with the expansion and the quotes.

This is what I'm trying:

subject="The Subject"
sender=From:Sender\<someone@example.com\>
recipient_list=me@example.com,another@example.com,yetanother@example.com

report="mail -s "$subject" -a $sender $recipient_list"

...
$report <<< "A log message from a section of script"
...
$report <<< "A different log message"

The trouble is with $subject.
Calling mail -s "$subject" -a $sender $recipient_list <<< "My Message" works nicely, but wrapping it into a variable as I've done above ends up sending the email with only the first word of "The Subject" getting sent, not the whole string.

I'm going to go the proper function route, but now I'm curious. I'm sure some escape/expansion trick will do it, but I have not been able to find the correct one (or reason it out).

Thanks!

dabell
  • 60
  • 10
  • Obligatory link to http://mywiki.wooledge.org/BashFAQ/050. – chepner Feb 02 '16 at 19:03
  • @chepner thanks, but already in my initial question – dabell Feb 02 '16 at 19:16
  • Have you read the page? It explains why your attempt to embed quotes in the variable's value fails. – chepner Feb 02 '16 at 19:17
  • There is no solution with a simple string, no matter how you escape characters, because shell strings are just strings. The fact that part of the string was escaped when the string was created is not stored anywhere in the string. You could use `eval`, but that's ugly. You could use an array (which would be easy). Or you could use a function (which would be portable). – rici Feb 02 '16 at 19:33
  • @chepner I did read the page, but don't think I fully grasped it. Will try to dig deeper. Cheers! – dabell Feb 02 '16 at 19:36
  • @rici I have opted for the function route, although I'm happy to have learned the array option. `function report { mail -s "$subject" -a $sender -A $log_file $recip_list <<< "$1" }` The `"$1"` allows me to call it thus (with embedded newline): `report "There were $num_errors errors reported. "$'\n'"See attached file."` – dabell Feb 02 '16 at 19:39
  • @dabell: I like the array solution myself, but tastes vary. – rici Feb 02 '16 at 20:07

1 Answers1

2

The answer, of course, is use an array.

report=(mail -s "$subject" -a "$sender" "$recipient_list")

 ...

"${report[@]}" <<< "A log message from a section of script"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358