Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers 3

up vote 3 down vote accepted

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
share|improve this answer
    
This one looks like the most universal. –  mdpc Aug 21 '13 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 '13 at 17:53
add comment

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.

share|improve this answer
    
I like this but it will not work on all UNIX/Linux systems. SunOS for one. –  mdpc Aug 21 '13 at 17:15
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.