Harkirat Singh Lamba
Harkirat Singh Lamba

Reputation: 31

How to replace value of place holder

I am new to shell programming. I have two files:

  1. eg.txt
  2. file.sh

The eg.txt file has some HTML content and file.sh cotains a shell script. In the script a value is assigned to the temp variable, and that value should be injected into the HTML file.

eg.txt

<html>
  Hi MGM ,<br/>
  One alert has been received !!<br/>

 Here is the event Data.<br/><br/>

 <font size=‘1’>{temp}</font>
 <br/><br/>
 Regards,
 WDTS Supports.
 </html>

file.sh

echo $1
temp=56

(
echo "To:"$1
echo "Subject: Alert Updates !! "
echo "Content-Type: text/html"

echo cat eg.txt
) | /usr/sbin/sendmail -t

echo "Mail sent !!"

Upvotes: 1

Views: 97

Answers (3)

sjsam
sjsam

Reputation: 21965

I have introduced some error checking to your code :

#!/bin/bash
temp=56
if [ -z "$1" ]
then
echo "Usage : ./file.sh user_name_to_mail to"
exit -1
else
    if id "$1" >/dev/null 2>&1 #Check if user exists, suppress stdout, stderr
    then
      mail_header=$(echo -e "To: $1\nSubject: Alert Updates"'!!'"\nContent-Type: text/html\n")
      mail_body=$(awk -v var="$temp" '{print gensub(/{temp}/,var,"g"$0)}' eg.txt)
      echo -e "$mail_header\n$mail_body" | sendmail -t                   
    else
      echo -e "Sorry! Invalid User\n"
      exit -1 # The error code is set to  detect failure
    fi
fi

To prevent the mails going to spam you need to have a valid SPF record for domain from which you're sending email. Check [ this ] for a starting point.


Note:

! is a special character to bash, it is used to refer to previous command. To work around this problem I have used ..Updates"'!!'"\nContent-Type...

Inside the single quotes the ! loses its special meaning.


Interesting reads :

  1. What is an [ SPF ] record?
  2. Open SPF [ documentation ] .

Upvotes: 2

SLePort
SLePort

Reputation: 15461

With sed :

sed "s/{temp}/$temp/" eg.txt | /usr/sbin/sendmail -t

You can also use printf to inject variables in your template :

file.sh

temp=56
tpl=$(cat "eg.txt")

printf "$tpl" "$1" "$temp" | /usr/sbin/sendmail -t

eg.txt

To:%s
Subject: Alert Updates !!
Content-Type: text/html

<html>
  Hi MGM ,<br/>
  One alert has been received !!<br/>

 Here is the event Data.<br/><br/>

 <font size=‘1’>%s</font>
 <br/><br/>
 Regards,
 WDTS Supports.
 </html>

Update:

If multiple variables, just write multiple substitute commands (and update placeholders in eg.txt):

sed "s/{temp1}/$temp1/;s/{temp2}/$temp2/" eg.txt | /usr/sbin/sendmail -t

Upvotes: 3

Chet
Chet

Reputation: 1225

echo $1
temp=56

    (
    echo "To:"$1
    echo "Subject: Alert Updates !! "
    echo "Content-Type: text/html"

    awk -F "" -v var=$temp '{gsub(/{temp}/,var,$0); print}' < eg.txt 
) | /usr/sbin/sendmail -t

echo "Mail sent !!"

added awk to '|' where the temp is stored in awk variable : var which is later replaced

awk -F "" -v var=$temp '{gsub(/{temp}/,var,$0); print}'

Upvotes: 1

Related Questions