Mail from a shell script?

Jez Hancock jez.hancock at
Mon Sep 13 19:01:35 PDT 2004

On Mon, 13 Sep 2004 11:31:55 -0600 (MDT), Ryan Sommers
<ryans at> wrote:
> First problem I ran into. I'm attempting to send the mail via `which
> mail`. I first was going to attempt to concatenate the message via
> "message=${message}$'\n'<other line>" However, this strips the newlines
> out of the variable (both sh and bash). I then tried using the <<string
> redirection in bash/sh and same thing happened.
I believe this happens because the default input field separator (the
environment variable $IFS) is set to space by default and so newlines
are just 'squashed'.  Effectively all newlines are stripped out.

As a test you can try this:


This is a test.

Another line.

Last line."

# OFS="$IFS"
# IFS=""
echo "$message"
# IFS="$OFS"

If you run the script once with the commented lines, you should see
the same problem you've encountered already.  Newlines are replaced
with spaces.

However if you then remove the comments so that the $IFS variable is
unset before echoing the message (first saving the original value to
$OFS) and run it, the script should display the lines as intended,
newlines intact.  Finally the last commented line resets $IFS to it's
original value - script execution can be messed up later if you don't
do this.

> My next thought was to open an fd through which to pipe output since the
> shells support it. However, it seems they only support opening a file for
> read/write, not a pipe.
> So, my ultimate question is, is there any way to send an email from a
> shell script without creating a "wrapper script" that pipes the output of
> one script into the mail program. Ie script1 contains only "script2 | mail
> <recip>".

You can always try this as well to find scripts that contain the kind
of code you want to emulate:

file /usr/local/bin/* | grep Bourne | cut -f1 -d: | xargs grep mail

which gives you a list of bourne shell scripts residing in
/usr/local/bin that contain reference to the string 'mail' - those
scripts that might contain mailer code.

Running this now I remember checking out the 'flea' script before for
an example before - another is the freebsd problem report script -
send-pr.  I think those scripts cat the message content out to a
temporary file first and then pipe that file back to the sendmail
command - or some variation on that theme.

Jez Hancock
 - System Administrator / PHP Developer  - Another FreeBSD Diary        - ipfw peruser traffic logging

More information about the freebsd-questions mailing list