How can a bash script detect if it is running in the background?

Quoting man ps:

PROCESS STATE CODES

   Here are the different values that the s, stat and state output
   specifiers (header "STAT" or "S") will display to describe the state of
   a process.
   ...
   +    is in the foreground process group

So you could perform a simple check:

case $(ps -o stat= -p $$) in
  *+*) echo "Running in foreground" ;;
  *) echo "Running in background" ;;
esac

Look at the file /etc/bash.bashrc".

The line that has "$PS1". Then do a "man bash" and look for the token PS1.

[ -z "$PS1" ] && return

exits a script that is not interactive.


All the previous solutions involve spawning processes, etc.. Very, very ugly, since .bashrc is called every time a bash shell launches, hence those solutions end launching 1000's of processes.

Much cleaner is asking bash itself: bash has a predefined variable $- that has "i" if its running in an interactive shell. For example, putting this into your .bashrc is much cleaner and much cheaper and, most importantly, will always work!

case "$-" in 

    *i*) # interactive shell

    ;;
esac

Tags:

Shell

Bash