Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

Is there way for a bash script to know if it is running in the foreground or background, and so it can behave slightly differently in each case?

share|improve this question
Note that a process can move from foreground to background and vice versa because of job control. – Barmar Mar 12 '14 at 18:45
You may also be interested in knowing if the script is running from an interactive shell – GnP Mar 18 '14 at 15:45
up vote 19 down vote accepted

Quoting man ps:


   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" ;;
share|improve this answer

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.

Hope this helps.

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.