1

I want to echo to the terminal if the script is being executed by me, in the flesh or I want to echo to a log file if it is being done via a cron job.

Ubuntu 16.04

example:

#!/bin/bash

if [ ***** ]; then
   echo "You executed this script just now !";
else
   echo "You were executed by the server cron at ${date}" >> example.log
fi

I rewrote the above because I thought it would be a simpler way to explain it. It's a more direct and cleaner example.

Vituvo
  • 337
  • 2
  • 5
  • 16

3 Answers3

2

Try this :

if [[ -t 0 ]]; then
    echo "executed from terminal"
elif [[ $(< /proc/$PPID/comm) == cron* ]]; then
    echo "executed by cron"
else
    echo "executed outside of a terminal"
fi
Gilles Quénot
  • 1,313
  • 10
  • 17
0

As an option you can set an environment variable in your crontab file and then let the script check for the variable. I.e. in you crontab add CRON=yes

in your script

if [[ "$CRON" = "yes" ]]; then

or simply check if $CRON is defined [[ -z "$CRON" ]]

-1

Super easy way: just create a file before.

# m h  dom mon dow   command
* * * * * /usr/bin/touch /tmp/FOO && /your_script/

[ -f /tmp/FOO ] && echo "Executed by crontab"; rm /tmp/FOO || echo "I'm physically executing"
Zurg
  • 1