Alex Rivera | Logout

Can a bash script tell if it's being run via cron?

Asked 2010-07-09T17:09:11.240
35

Not having much luck Googling this question and I thought about posting it on SF, but it actually seems like a development question. If not, please feel free to migrate.

So, I have a script that runs via cron every morning at about 3 am. I also run the same scripts manually sometimes. The problem is that every time I run my script manually and it fails, it sends me an e-mail; even though I can look at the output and view the error in the console.

Is there a way for the bash script to tell that it's being run through cron (perhaps by using whoami) and only send the e-mail if so? I'd love to stop receiving emails when I'm doing my testing...

Edit
Report

1 Answer

12

Here's two different options for you:

  • Take the emailing out of your script/program and let cron handle it. If you set the MAILTO variable in your crontab, cron will send anything printed out to that email address. eg:

    MAILTO=youremail@example.com
    # run five minutes after midnight, every day
    5 0 * * *       $HOME/bin/daily.job
    
  • Set an environment variable in your crontab that is used to determine if running under cron. eg:

    THIS_IS_CRON=1
    # run five minutes after midnight, every day
    5 0 * * *       $HOME/bin/daily.job
    

    and in your script something like

    if [ -n "$THIS_IS_CRON" ]; then echo "I'm running in cron"; else echo "I'm not running in cron"; fi
    
answered 2010-07-09T17:33:23.747

Your Answer