0

I do some automatic checks and want to send a mail if a file has changed. I want the mail body to contain the new version of the file, some static text and the old version of the file, so what I do is

 cat mettab.txt metalerttext.txt mettab.old.txt  | /usr/bin/mail -s Metalerts (...)

where mettab.txt is the new version, metalerttext.txt is a static file and mettab.old.txt is the old version.

but, rather than using metalerttext.txt, I feel it would be better to use a heredoc. But is it possible to do that in a single line as above, or is the only possibility to make a temporary file and do something like:

 cp mettab.txt mailtemp.txt
 cat <<EOF
    some text from metalerttext.txt
 EOF  >> mailtemp.txt
 cat mettab.old.txt >> mailtemp.txt

before mailing mailtemp.txt and deleting the file.

Or have I overlooked someting? (metalerttext.txt is just one line)

0

2 Answers 2

5

As mentioned in the comments, yes:

$ cat start.txt - end.txt <<'EOF' | /usr/bin/mail ...
some contents
EOF

The - explicitly tells cat to read from stdin, i.e. plain cat does the same as cat - (unless there's some slight difference wrt. error messages or such). You can also put the redirection first on the line, <<'EOF' cat ....


If your system has /dev/fd/N, then you can even use multiple here-docs on the same command...:

$ echo hello > hello.txt
$ cat /dev/fd/3 hello.txt /dev/fd/4 3<<'END3' 4<<'END4' > output.txt
three
END3
four
END4
$ cat output.txt
three
hello
four
1

Here is a solution using command substitution

echo "$(cat mettab.txt)
    some text from metalerttext.txt
$(cat mettab.old.txt)" | /usr/bin/mail ...

but remember that

  • you have to escape characters, or they will be interpreted by the shell (advantage?).
  • Be sure that the files mettab.txt and mettab.old.txt exist. If they don't, it will output a blank line and show messages to stderr.
  • If you are using bash, you can use $(< mettab.txt) instead of $(cat mettab.txt) as stated in the manual.

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.