6

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
checker284
  • 1,286
  • 3
  • 14
  • 29
  • Use environment variables? `* * * * * CRON_FIRED=true /path/to/myscript` but note that the syntax is [subject to the cron implementation](http://stackoverflow.com/a/10657111/2908724) and can also be fooled trivially. – bishop Oct 26 '15 at 20:24

1 Answers1

8

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.

ghoti
  • 45,319
  • 8
  • 65
  • 104
  • Thx, seems to be the solution. I always forget, where I can find the list of available 'if' test parameters like -n, -x, -f as well as your used -t. Where can I find this list? I want to read, what exactly the '-t' means. POSIX means, that it works on every Linux Distributation, right? – checker284 Oct 26 '15 at 20:43
  • 1
    @user2966991 that would be http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html or `man 1p test` – Alois Mahdal Oct 26 '15 at 20:50
  • 1
    @user2966991 In this case POSIX means it should work with any POSIX-compliant shell. Such shells can also be found on Windows, and technically, you can have a Linux distro without a POSIX shell. – Alois Mahdal Oct 26 '15 at 20:52
  • 1
    Great, thanks! For posterity, I should just add to Alois' comment, that the `1p` man section is not universal, and that on the systems I use (FreeBSD, OSX and Ubuntu), `man 1 test` or even just `man test` will show you the list of things that can be tested. Since you're running Linux, it's entirely likely that you also have `bash` available. If so, you can `man bash` and search for the section, "CONDITIONAL EXPRESSIONS" to see the extended test notation that bash provides using the `[[` conditional command. (Spoiler: bash also provide `-t`.) – ghoti Oct 26 '15 at 21:11