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
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With