home | list info | list archive | date index | thread index

Re: [OCLUG-Tech] how does one test if bash shell is interactive

  • Subject: Re: [OCLUG-Tech] how does one test if bash shell is interactive
  • From: "Ian! D. Allen" <idallen [ at ] idallen [ dot ] ca>
  • Date: Tue, 9 Aug 2005 13:54:46 -0400
Vic Gedris wrote:
> michael ondrechak wrote:
> > Is there a way for a bash script to test if it's being run from an
> > interactive shell? That is, I want to be able to test whether the
> > script was started as:
> > $ script
> > or as
> > $ script &
> This should answer it:
> http://theory.uwinnipeg.ca/localfiles/infofiles/bash/bashref_54.html

Nope.  "man bash":
    An interactive shell is one started without  non-option  arguments  and
    without the -c option whose standard input and error are both connected
    to terminals (as determined by isatty(3)), or one started with  the  -i
    option.   PS1 is set and $- includes i if bash is interactive, allowing
    a shell script or a startup file to test this state.

You will note that it says nothing about foreground/background ("&").

Michael needs to clarify his question, given that "&" has nothing to do
with a shell being interactive, nor does the use of "&" have anything
to do with whether the shell that used it is itself an interactive shell.
(Both interactive and non-interactive shells can start scripts using "&".)

If I ignore the question and concentrate on his wanting to test whether
the script was started as "script &", we still need to know whether he
wants exactly what he says (the script was *started* in the background,
but may or may not be currently) or whether he wants to check the
*current* foreground/background status of the script (which can change
from second to second as you type ^Z and fg/bg at it).  Alas, I don't
think there are easy answers to either question.

The only thing that makes a script "backgound" is that the shell that
started it isn't waiting for the script to complete before prompting for
more commands.  Finding out whether or not the parent shell is currently
waiting for the current script isn't easy.  (I don't know how to do it
without doing messy unportable things with process memory.)

You can do some kludges with process group testing under shells that
do job control - if the process group of this script isn't the same as
the process group of the terminal, it's probably a background script.
(But this test fails if the shell isn't doing job control, or if there
is no terminal at all.)

-- 
-IAN!  Ian! D. Allen       Ottawa, Ontario, Canada - www.ottawa.ca
       EMail: idallen [ at ] idallen [ dot ] ca   Home Page: http://www.idallen.com/
       College professor (Linux) via: http://teaching.idallen.com/
       Support free and open public digital rights:  http://eff.org/