3

I'd like to use the same scripting for cron and interactive, just wondering if there was a universal way over UNIX/Linux systems to easily make this determination.

3 Answers 3

4

You can try to return the name of the parent process with something like this: -

ps -ocommand= -p $PPID | awk -F/ '{print $NF}' | awk '{print $1}'

For me this returned konsole when I ran this interactively.

or you could script in some logic to handle situations.

while getopts cm opt
do
case $opt in
        c)
                ##  Do crontask 
        ;;
        m)
                ##  Do manual
        ;;
        esac
done

Now when executing the script you can pass an option as an attribute like so :-

/use/local/bin/example.sh -m
/use/local/bin/example.sh -c
2
  • This one looks like the most universal.
    – mdpc
    Aug 21, 2013 at 17:15
  • I know that I did not ask this, but cron (in RHEL) also runs at jobs. So there it doesn't look like there is a way to distinguish at jobs from cron jobs in cases.
    – mdpc
    Aug 21, 2013 at 17:53
2

there is no universal way at all. using interactive/noninteractive shell detection or tty detection is not reliable either, as other cases than cron can have these characteristics. just add a variable in your cron entry. say you need to run test.sh, then use this instead.

$ RUNENV=cron ./test.sh
cron
cat ./test.sh 
#!/bin/sh
echo $RUNENV

This is fairly easy and reliable, if you control the cron setup.

1
  • I like this but it will not work on all UNIX/Linux systems. SunOS for one.
    – mdpc
    Aug 21, 2013 at 17:15
1

I don't know how portable this is, but on Linux you can run tty and check whether the output is a tty.

$ tty
/dev/pts/2
$ crontab -e
* * * * * echo $(tty) >> /home/paulo/cron_tty
[Wait a minute...]
$ cat /home/paulo/cron_tty
not a tty

Note that the tty will also not be set if the script is running non-interactively from something other than cron, but since you said you want to distinguish cron from interactive, that shouldn't be an issue.

Other than that, possibly the most robust solution is to add a switch to your script, telling it whether it is running from cron or not, as suggested in a Stack Overflow question.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .