Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 200
user2966991 Avatar asked Oct 26 '15 20:10

user2966991


People also ask

How do I know if a cron job is executed in Linux?

Running the “systemctl” command along with the status flag will check the status of the Cron service as shown in the image below. If the status is “Active (Running)” then it will be confirmed that crontab is working perfectly well, otherwise not.

How do I know if a cron script is running?

To check to see if the cron daemon is running, search the running processes with the ps command. The cron daemon's command will show up in the output as crond. The entry in this output for grep crond can be ignored but the other entry for crond can be seen running as root. This shows that the cron daemon is running.

How do I test a cron script?

How to test a Cron Job? Open the Corntab – Its an online tool that will help you to Check the Cron time. You can enter the cron time and it will tell you when this cron will trigger. Note down the time and verify if its correct one.


1 Answers

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.

like image 142
ghoti Avatar answered Sep 23 '22 17:09

ghoti