views:

156

answers:

2

Hi

I have to write a script to send mails thru unix shell scripts.

The following script allows me to have variable message body.

Is it possible to have a variable subject part in the bellow code??


#!/bin/bash
# Sending mail to remote user

sender="[email protected]"
receiver="[email protected]"
body="THIS IS THE BODY"
subj="THIS IS THE SUBJECT."


echo $body | mail $receiver -s "THIS IS THE SUBJECT" // this works fine
echo $body | mail $receiver -s $subj // ERROR - sends one mail with only
//"THIS" as subject and generates another error mail for the other three words


+5  A: 

You forgot the quotes:

echo $body | mail $receiver -s "$subj"

Note that you must use double quotes (otherwise, the variable won't be expanded).

Now the question is: Why double quotes around $subj and not $body or $receiver. The answer is that echo doesn't care about the number of arguments. So if $body expands to several words, echo will just print all of them with a single space in between. Here, the quotes would only matter if you wanted to preserve double spaces.

As for $receiver, this works because it expands only to a single word (no spaces). It would break for mail addresses like John Doe <[email protected]>.

Aaron Digulla
+2  A: 

you can use mailx and always put your quotes around variables

mailx -s "$subj" [email protected] < myfile.txt