How can i log error from my script.sh every time I run the script.sh and save output to a file?
Asked Answered
E

3

7

How can I save the error output when running my script to a file? I have my code bellow, but the code does not track error and save the error to test.log14. Can somebody give me a hint on what could be wrong in my code...

 LOGFILE=/usr/local/etc/backups/test14.log

 "$(date "+%m%d%Y %T") : Starting work" >> $LOGFILE 2>&1
Ethelstan answered 28/1, 2015 at 13:14 Comment(2)
You seems to have missed "echo" before "$(date "+%m%d%Y %T") : Starting work" >> $LOGFILE 2>&1Guereza
@VineethVenugopal Ok, I missed the echo, thanks. But the code is not saving error output to my file.Ethelstan
O
6

There are normally 2 outputs that you see on your screen when you execute a command:

  1. STDOUT
  2. STDERR

You can redirect them independently per command.

For example:

ls >out 2>err

will give you two files; out will contain the output from ls and err will be empty.

ls /nonexisting 1>out 2>err

will give you an empty out file and err will contain

"ls: cannot access /nonexisting: No such file or directory"

The 2>&1 redirects 2 (STDERR) to 1 (STDOUT)

Your echo does not have any errors, therefore there is no output on the STDERR.

So your code would probably need to be something like this:

echo "$(date "+%m%d%Y %T") : Starting work"
work_command > work_output 2>> $LOGFILE
Oquassa answered 2/10, 2016 at 17:17 Comment(0)
G
5

Use this code:

#!/bin/bash

LOGFILE=/usr/local/etc/backups/test14.log

(
    echo "$(date "+%m%d%Y %T") : Starting work"
    ... more commands ...
    echo error 1>&2 # test stderr

    echo "$(date "+%m%d%Y %T") : Done"
) >& $LOGFILE

The () makes BASH execute most of the script in a subshell. All output of the subshell (stderr and stdout) is redirected to the logfile.

Ganger answered 28/1, 2015 at 13:36 Comment(2)
Nice code, but the output in the logfile is not displaying the wrong command that i used, the error command.Ethelstan
@V.V.T: It works for me. My guess is that you're omitting some vital information. Edit your question: Show us more of the script, what output you get and what output you expect.Ganger
T
4

Send the error output of the command instead of appending 'error output from append' -if that makes sense. I typically use functions for this type of process (similar to above.)

Try this:

2>&1 >> $LOGFILE

instead of

>> $LOGFILE 2>&1

###
function run_my_stuff {
    echo "$(date "+%m%d%Y %T") : Starting work"
    ... more commands ...
    echo "$(date "+%m%d%Y %T") : Done"
}
## call function and append to log
run_my_stuff 2>&1 >> ${LOGFILE} # OR
run_my_stuff 2>&1 | tee -a ${LOGFILE} # watch the log
Tobey answered 29/1, 2015 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.