Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve new line characters for sendmail in bash script?

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.

like image 335
Larry Avatar asked Nov 29 '22 11:11

Larry


2 Answers

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.

like image 150
postsasaguest Avatar answered Dec 04 '22 04:12

postsasaguest


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
like image 44
AnFi Avatar answered Dec 04 '22 05:12

AnFi