Re: shell script: How to determine if I'm in the background?
Carlos Sousa <email@example.com> writes:
> I've just spent one hell of a time trying to find the best code for a
> shell script to determine if it is running in the background. I need this
> for a cd backup script that will pause for keyboard input if it is run
> from the command line, but should go ahead if invoked by cron.
> I was surprised to realize that this turns out to be a little more
> complicated than I thought it should be. After STFWing and RTFMing of the
> bash man page I came up with a series of three tests (existence of an
> attached tty, availability of file descriptor 0, and process group ID
> being equal to the terminal process group ID for any process called by
> the script), the failure of any of which would mean the we're in the
> background. I think perhaps the last one should be enough, though...
> The first 2 tests are clearly not enough.
> I'd very much like to hear from anybody who might have faced the same
> problem and learn of possibly simpler alternative solutions. I enclose
> the code below.
> Grateful for your comments.
In bash (as you are using) is very easy: Check the variable $- . The
keyword here is "interactive shell". From the bash man page:
"PS1 is set and $- includes i if bash is interactive, allowing
a shell script or a startup file to test this state."
"To determine within a startup script whether or not Bash is running
interactively, test the value of the `-' special parameter. It
contains `i' when the shell is interactive. For example:
case "$-" in
*i*) echo This shell is interactive ;;
*) echo This shell is not interactive ;;