Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This is how I log both stdout and stderr in my scripts (usually cronjobs):

#!/bin/bash
mylog() {
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] $1"
}
(
mylog 'start'

some-command || mylog 'error' && exit 1

mylog 'end'
) >> /var/log/my-log.log 2>&1

In some scripts I use return instead of exit and works fine, but now it says that I can't use return unless I include the script with src or use it in a function. So I changed it to exit, but the problem is that it doesn't log anything, it seems like it stops the >> output redirection. Another problem is that I won't be able to include it later with src, because I only want to stop this script, not everything.

I use output redirection because I want to log everything, even if no error occurred. And sometimes commands don't even return proper exit codes, so I can't trust that.

So how can I 'return' on error? I know about 'set -e', but I prefer having more control over when to stop the script.

Any thoughts?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

I cannot explain the behavior you are experiencing, but here is a possible fix:

#!/bin/bash
mylog() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

mymain() {
    (
        mylog 'start'

        some-command  ||  mylog 'error'  &&  return 1

        mylog 'end'
    ) >> /var/log/my-log.log 2>&1
}

mymain

Alternatively, remove the redirection from the mymain function definition and put it on the mymain function call:

mymain >> /var/log/my-log.log 2>&1

(You should be able to delete the parentheses from the mymain function definition then, too.)  Alternatively, since you want IO to be redirected for the entire script, you can break the redirection apart from the action statements:

exec >> /var/log/my-log.log
exec 2>&1
mymain

Since I don’t understand why your approach is failing, I cannot explain why any of the above are any more likely to work as desired.  However, they are slightly different ways of doing the same thing, and that might be just enough.  By the way, I changed `date …` to $(date …) just for general reasons; I don’t believe that has anything to do with your problem.

share|improve this answer
    
Yes, I thought of using mymain. That might be enough, I will try that, thanks. –  ChocoDeveloper Jan 5 '13 at 22:09
add comment

How about using the screen command in linux? This would due the trick unless you are heart set on programming a solution yourself.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.