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

you can try "tty" to see if it's run by a terminal or not. that won't tell you that it's specifically run by cron, but you can tell if its "not a user as a prompt".

you can also get your parent-pid and follow it up the tree to look for cron, though that's a little heavy-handed.


I had a similar issue. I solved it with checking if stdout was a TTY. This is a check to see if you script runs in interactive mode:

if [ -t 1 ] ; then 
    echo "interacive mode";
else
    #send mail
fi

I got this from: How to detect if my shell script is running through a pipe?

The -t test return true if file descriptor is open and refers to a terminal. '1' is stdout.


Why not have a command line argument that is -t for testing or -c for cron.

Or better yet:

[email protected]

If it's not specified, don't send an email.

Tags:

Bash

Cron