Thursday, January 22, 2009

Debug - Running A Crontab Script Interactively

If your script needs to run in cron, you wouldn't want any output (stdout/stderr) to send to the cron because it will be ended up in your mail box. You may want to consider the below approach to auto set your script to 'debug' mode if you are running in an interactive shell.

If you login to an interactive shell, tty command will give you a pseudo terminal. Whereas if you run tty in a at/cron environment, you will get a "not a tty".

$ tty
/dev/pts/3

$ at now
at> tty > somefile
at> <EOT>
job 20 at 2009-01-22 21:37

$ cat somefile
not a tty

Now we can take advantage of tty so that when you run your cron job in an interactive shell, you are actually telling it to run in a 'debug' mode.

_debug_=1
if [ "`tty`" = "not a tty" ]; then
   _debug_=0
fi

debug()
{
    if [ $_debug_ = 1 ]; then
       if [ "$1" = "-x" ]; then
           shift
           $*
       else
           echo $*
       fi
    fi
}


debug This is a comment
debug -x uname -a

Useful ?

Labels:

0 Comments:

Post a Comment

<< Home