Bash – How to a bash script detect if it is running in the background

bashshell

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?

Best Answer

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