Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 4 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
case $opt in
                ##  Do crontask 
                ##  Do manual

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

/use/local/bin/ -m
/use/local/bin/ -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

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, then use this instead.

$ RUNENV=cron ./
cat ./ 
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

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

$ tty
$ 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

Your Answer


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.