6
#!/bin/bash
MESSAGE="Line one. /n"

MESSAGE="$MESSAGE Line two. /n"
MESSAGE="$MESSAGE Line three."

echo $MESSAGE | mail -s "test" "[email protected]"

Is that how I should get each line, on its own line?

2
  • Jim, welcome to StackOverflow. Please remember to format your code samples by selecting them and hitting the "code" button (the one with ones and zeros on it). Commented Feb 16, 2010 at 19:14
  • 1
    Thanks for the code button tip :) Commented Feb 16, 2010 at 20:05

3 Answers 3

16

Use a heredoc.

mail -s "test" "[email protected]" << END_MAIL
Line one.
Line two.
Line three.
END_MAIL
Sign up to request clarification or add additional context in comments.

1 Comment

If you quote the first delimiter (here END_MAIL) it will prevent parameter expansion, command substitution, etc., which may be desirable.
9

Change:

echo $MESSAGE | mail -s "test" "[email protected]"

To:

echo -e $MESSAGE | mail -s "test" "[email protected]"

1 Comment

This should be the accepted answer. The -e switch expands the \n newline characters as expected and is easier to use in a script on a single line than the heredoc method.
2

The heredoc advice is good, plus you might want to consider using mailx for which there exists a Posix standard or perhaps sendmail which will exist if the mailer is either sendmail or postfix. (I'm not sure about qmail.)

Unless using sendmail, it's also a good idea to set the MAILRC variable to /dev/null to bypass the user's configuration script, if any.

1 Comment

I'm a big fan of using sendmail in shell scripts. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.