APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

How to tell if script is running in background

The method given below will work under some conditions, but I'd use "tty", which will return "not a tty" if in background.

The usual reason for wanting to know is to shut up output to avoid wasting time and possibly filling up a log file.

Here is an answer for Perl.

From: spcecdt@deeptht.armory.com. (John DuBois)
Newsgroups: comp.unix.sco.misc
Subject: Re: detecting background process
Date: Tue, 27 Apr 1999 10:16:13 GMT
Message-ID: <925208173.823.10@news.remarQ.com> 

In article <37621AF0.7DB8BDDA@ncs.co.nz>, Greg M Lee  <greg@ncs.co.nz> wrote:
>I use:
>if [ -t 0 ];then
>        echo "running in foreground"
>        echo "running in background"
>Art L. wrote:
>> I am sure there is a better way, but a method I use is to look at the
>> return of the tty command.
>> #!/bin/sh
>> if [ '`tty`' = "not a tty" ];then
>>         echo "running in background"
>> else
>>         echo "running in foreground"
>> fi
>> On 21 Apr 1999 19:29:28 GMT, "Gino Facini" <gino.facini@gov.nb.ca>
>> wrote:
>> >I'm fairly new to Unix scripting and I need to know if the script that is
>> >running was started in the background or not.  If anyone has an easy way of
>> >telling this could you please email me personally at gino.facini@gov.nb.ca
>> >

Are you using sh or ksh?  If sh, the above solutions will work.  If ksh (or
another job-control shell), the handling of background jobs is more refined
with the result that the above won't work.  This method will work with both:

if {</dev/tty;} 2>/dev/null; then
    echo "running in foreground"
    echo "running in background"

John DuBois    spcecdt@armory.com.    KC6QKZ   http://www.armory.com./~spcecdt/

Got something to add? Send me email.

(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> How to tell if script is running in background ––>Re:detecting background process

Increase ad revenue 50-250% with Ezoic

More Articles by

Find me on Google+

© Tony Lawrence

Kerio Samepage

Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us

The easy confidence with which I know another man's religion is folly teaches me to suspect that my own is also. (Mark Twain)

This post tagged: