5

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
Bruno Alves
  • 51
  • 1
  • 1
  • 7

3 Answers3

5

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
Robert
  • 7,394
  • 40
  • 45
  • 64
Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31
4

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Nice code, but the output in the logfile is not displaying the wrong command that i used, the error command. – Bruno Alves Jan 28 '15 at 15:05
  • @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. – Aaron Digulla Jan 29 '15 at 09:06
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
Dale_Reagan
  • 1,953
  • 14
  • 11