I'm executing some script on my server startup, using the rc.local file (as suggested on this SQ answer.
The script sends an email to my address notifiying me that the server has started up.
This is the content of my /etc/rc.local file:
#!/bin/sh -e
echo "The $HOSTNAME server has started" | mail -s "[$HOSTNAME] start up" me@example.com
exit 0
Obviously, the
me@example.comis replaced by the correct value in the actual script
The script does execute at startup and I receive an email in my inbox, as expected... BUT! As the title implies, the $HOSTNAME is not replaced by the actual hostname of my server ; it's just blank. Here's the details of the email I receive:
Subject: [] start up
To: <me@example.com>
X-Mailer: mail (GNU Mailutils 3.4)
Message-Id: <20200131132017.0827D42DA2@example.com>
Date: Fri, 31 Jan 2020 14:20:16 +0100 (CET)
From: root <root@example.com>
The server has started
Notice the empty brackets in the subject, and the space between
Theandserveron the content.
What I expected, as you might have guessed from the rc.local content, was my hostname in the subject and the email content.
I tried executing the same command directly from the terminal, and that worked exactly as expected.
For some reason, when root is executing the command through the rc.local file on startup, it can not resolve the $HOSTNAME variable content and prints nothing instead.
I tried replacing $HOSTNAME by $(hostname -f) or even $(head -n1 /etc/hostname), but the result is exactly the same: no hostname in the received email...
What am I missing here?
EDIT:
I temporarily hardcoded the value in my rc.local script. So the command looks like:
echo "The server.example.com server has started" | mail -s "[server.example.com] start up" me@example.com
In this case, when the server does reboot, I receive my email as usual, with the content as expected... but the subject is still "[] start up"!
How can this be possible considering I hardcoded the value inside the brackets. Does the [] notation has a special meaning I am not aware of?