Search code examples
shellcroncron-task

How-to check if Linux shell script is executed by a cronjob?


Is it possible to identify, if a Linux shell script is executed by a user or a cronjob?

If yes, how can i identify/check, if the shell script is executed by a cronjob?

I want to implement a feature in my script, that returns some other messages as if it is executed by a user. Like this for example:

    if [[ "$type" == "cron" ]]; then
        echo "This was executed by a cronjob. It's an automated task.";
    else
        USERNAME="$(whoami)"
        echo "This was executed by a user. Hi ${USERNAME}, how are you?";
    fi

Solution

  • One option is to test whether the script is attached to a tty.

    #!/bin/sh
    
    if [ -t 0 ]; then
       echo "I'm on a TTY, this is interactive."
    else
       logger "My output may get emailed, or may not. Let's log things instead."
    fi
    

    Note that jobs fired by at(1) are also run without a tty, though not specifically by cron.

    Note also that this is POSIX, not Linux- (or bash-) specific.