with a shell script, it is possible to tell when it's run with cron vs run manually?
UPDATE:
it was asked why I want to know. My cron job will be logging, and i want to be able to log if someone is executing it manually.
|
with a shell script, it is possible to tell when it's run with cron vs run manually? UPDATE: it was asked why I want to know. My cron job will be logging, and i want to be able to log if someone is executing it manually. |
||||
|
|
In the times that I've needed to do this, i know it's a script that I'll never redirect to a file or to a pipe. So a simple test is to check if stdout (a.k.a file descriptor 1) is a tty (which it won't be from cron). In bash:
Again, warning, this is a test simply if your stdout is a tty. But works for my simple purposes. You could also check what your parent process is. In Linux, it can be as simple as:
|
|||||||||||||||
|
|
You could define a unique environment variable in your crontab:
I tested with this script:
When I ran from
When I ran from the command line manualy, output was:
|
|||
|
|
|
You can inspect the name of the parent process, which can be retrieved with However this is not necessarily a good idea (for example, you won't be able to easily test your cron jobs manually). Maybe if you explain why you want this someone can suggest a better solution. |
|||
|
|
|
You could create a special user for the cron job to run under. Then make your script readably by that user only, and put it in the user's crontab. That way, no other user can even read the script, let alone execute it. BTW, for a secure solution you need to make the cron script unreadable anyway. If other users can read the script, they can copy it, remove whatever cron-check mechanism you have and then run it, bypassing your logging if they want to. |
|||
|
|