2

I have a scheduled unix script that I want to log the output of. I am unable to edit the cron file due to the user interface restrictions, and I am unable to add >> logfile to the command. Is there something I can add within the script itself to send the output to a log?

{

printf poo

 #Do not change
PRINTF=/usr/bin/printf
MSMTP=/usr/local/bin/msmtp
MSMTPCONF=/var/etc/msmtp.conf

 #Can be changed
FROM="nas4free@usinfosec.com"
TO="dpatino@usinfosec.com"
MDIR="CaseData"
SUBJECT="$MDIR Backup Report"


} > /mnt/support/logs/$SUBJECT.log
#BODY="$(cat /mnt/support/logs/test.log)"
#$PRINTF "From:$FROM\nTo:$TO\nSubject:$SUBJECT\n\n$BODY" | $MSMTP --file=$MSMTPCONF -t
Daryl Patino
  • 29
  • 1
  • 1
  • 3

3 Answers3

6

Try

#!/bin/bash
exec > /tmp/myLog.log 2>&1
set -x

The log shows:

+ echo 'Hello World!'
Hello World!
lanes
  • 1,847
  • 2
  • 19
  • 19
3

One way is to wrap your script in braces and redirect the output as shown below:

#!/bin/bash
{
# script contents here
echo running script
} > logfile
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • I tried this and it worked until I added a variable in the logfile name. I've added my code to the question. – Daryl Patino Mar 18 '13 at 19:06
  • 1
    move the `SUBJECT` variable assignment outside the braces. – dogbane Mar 19 '13 at 08:14
  • @dogbane with this `>> logfile` I can append to the logfile, is it possible to "append to the top" in the logfile? Thanks a lot. – Jags Jul 16 '21 at 23:43
0

Append following line in starting of your script

log_file_path="/tmp/output.log"
log() { while IFS='' read -r line; do echo "$line" >> "$log_file_path"; done; };
exec > >(tee >(log)) 2>&1

Your script with modification

PRINTF=/usr/bin/printf
MSMTP=/usr/local/bin/msmtp
MSMTPCONF=/var/etc/msmtp.conf
FROM="nas4free@usinfosec.com"
TO="dpatino@usinfosec.com"
MDIR="CaseData"
SUBJECT="$MDIR Backup Report"

{

printf poo  


} > /mnt/support/logs/$SUBJECT.log
#BODY="$(cat /mnt/support/logs/test.log)"
#$PRINTF "From:$FROM\nTo:$TO\nSubject:$SUBJECT\n\n$BODY" | $MSMTP --file=$MSMTPCONF -t
Vivek Goel
  • 22,942
  • 29
  • 114
  • 186