Reputation: 596
Why isn't the following preserving the new line characters in the resulted email?
#!/bin/bash
file="/tmp/ip.txt"
address=$(curl -s http://ipecho.net/plain; echo)
ifconfig=$(ifconfig)
function build_body
{
echo "----------------------------------------------------------------" > $file
echo "IP Address: $address (according to http://ipecho.net/plain)" >> $file
echo "----------------------------------------------------------------" >> $file
echo >> $file
echo "Result from ifconfig:" >> $file
echo >> $file
echo "$ifconfig" >> $file
echo >> $file
}
build_body
msg=$(cat $file)
mail="subject:Home Server Status\nfrom:[email protected]\n$msg"
echo $mail | /usr/sbin/sendmail "[email protected]"
I receive the email this script generates, however, the whole body is all on one line! /tmp/ip.txt is exactly how I want the email to look.
Upvotes: 4
Views: 18929
Reputation: 111
I ran into this recently. I was able to resolve it adding the '-e' option to echo.
Change this:
echo $mail | /usr/sbin/sendmail "[email protected]"
To This:
echo -e "$mail" | /usr/sbin/sendmail "[email protected]"
Hopefully that helps.
Upvotes: 11
Reputation: 10913
You may use "here documents" (<<END
), make the function output its results to standard output.
#!/bin/bash
address=$(curl -s http://ipecho.net/plain; echo)
function build_body
{
cat <<END
----------------------------------------------------------------
IP Address: $address (according to http://ipecho.net/plain)
----------------------------------------------------------------
Result from ifconfig:
END
ifconfig
echo
}
( cat <<END; build_body) | /usr/sbin/sendmail -i -- "[email protected]"
Subject:Home Server Status
From:[email protected]
END
Upvotes: 5
Reputation: 113944
{
printf "subject:Home Server Status\nfrom:[email protected]\n\n"
cat "$file"
} | /usr/sbin/sendmail "[email protected]"
With echo $mail
, the contents of the file appear on the command line and bash processes them with word expansion. With cat "$file"
, the file name appears on the command line but the contents of the file do not and are thus safe from bash.
Upvotes: 2
Reputation: 4494
echo "$mail" | /usr/bin/sendmail ...
\n
between the headers and message:as in:
mail="subject:Home Server Status\nfrom:[email protected]\n\n$msg"
Upvotes: 4