How to check if linux shell cronjob script is running?

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

If yes, how can I identify / verify if the shell script is being executed by cronjob?

I want to implement a function in a script that returns some other messages as if they were being executed by the user. For example, for example:

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

One option is to check if the script is bound to 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 log things instead." fi 

Note that jobs launched by at(1) also run without tty, but not specifically with cron.

Please note that this is POSIX, not Linux- (or bash-).

+6
source

Source: https://habr.com/ru/post/1234558/


All Articles