Home > Blockchain >  Using SSH Bash Script to send a PHP mail including the content of a log file
Using SSH Bash Script to send a PHP mail including the content of a log file

Time:12-25

I used this command before:

mail -s "Logs" "[email protected]" < /srv/users/log/php7.4.error.log

to send the content of the error log file to my email address.

Now I am on another server and cannot use mail anymore, but found PHP as alternative:

php -r 'mail("[email protected]", "Logs", "Content", "From:[email protected]");'

How can I use the bash (mail.sh file) to not sent "Content" but the content of /srv/users/log/php7.4.error.log instead?

Can I declare a variable? And then insert a $content var inside the bash script?


In the shell script I tried:

LOGFILE = /srv/users/log/php7.4.error.log; 
php -r 'mail("[email protected]", "Logs", $LOGFILE, "From:[email protected]");';

without success. Error is: "Warning: Undefined variable $LOGFILE in Command line code on line 1"

CodePudding user response:

You can save the file content as a variable and use it as an argument

my_log=$(cat /srv/users/log/php7.4.error.log)
php -r "mail('[email protected]', '$my_log', 'Content', 'From:[email protected]');"

This can also be written as

php -r "mail('[email protected]', '$(cat /srv/users/log/php7.4.error.log)', 'Content', 'From:[email protected]');"

You can also use proper open/read PHP functions and only pass the file name from bash

#!/usr/bin/env bash
set -eu
file_name="$1"

php -r "
$myfile = fopen('$file_name', 'r') or die('Unable to open file!');
mail ... // consume php myfile variable;"

Keep in mind, you need to substitute bash variable in single/double quotes and do add proper escape characters if needed

  • Related