shellcronpipe

Cron redirect stdout and stderr to different files


I'm using a python script with python-crontab to generate job entries in the crontab, and execute them every minute.

I'm doing something like:

my_cron = CronTab(user=getpass.getuser())
job = my_cron.new(command=pathname+'/cron_restart.sh >> ' + pathname + '/log_listener.txt 2>&1')
job.minute.every(1)
my_cron.write()

so that the crontab entry will look like (with the correct pathname, clearly)

* * * * * __pathname__/cron_restart.sh >> __pathname__/log_listener.txt 2>&1

This way, I'm redirecting both the stdout and stderr to the log_listener.txt file. Is it possible to split them, and send them to two different files?


Solution

  • This way, I'm redirecting both the stdout and stderr to the log_listener.txt file. Is it possible to split them, and send them to two different files?

    You're redirecting both to log_listener.txt because you specifically asked that stderr (2)'s output be redirected (>) to stdout (&1).

    If that's not what you want, don't do that?

    > f is a shortcut for 1>f which redirects output (>) from stdout (1) to the file f, truncating it if it exists.

    2 is stderr, so you can just 2> to some other file in order to redirect stderr to a different file than stdout. >> is an appending redirection so 2>> will append stderr to an existing file (or create it) in the same way >> does for stdin.

    Therefore you can just have a command of

    cron_restart.sh >> log_listener.txt 2>>log_error.txt
    

    to log stdout and stderr to different files.