checker284
checker284

Reputation: 1316

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

Upvotes: 6

Views: 1717

Answers (2)

Seamus
Seamus

Reputation: 223

Assuming you have a version of cron that allows you to set environment variables, you could do this:

Open your crontab for editing & add a variable as follows:

crontab -e

## in the crontab, add this line:

RUN_BY_CRON="TRUE"

## save & exit editor

In a script that you run from cron, add the following lines to test for the RUN_BY_CRON variable:

#!/usr/bin/bash
set -u                              # this line is optional
...
RUN_BY_CRON=${RUN_BY_CRON-""}       # shell parameter expansion
...
if [ "$RUN_BY_CRON" = "TRUE" ]; then
    echo "script $0 is RUN_BY_CRON"
else
    echo "script $0 is NOT RUN_BY_CRON"
fi

Upvotes: 0

ghoti
ghoti

Reputation: 46846

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.

Upvotes: 8

Related Questions