bash 脚本如何检测它是否在后台运行?

dan*_*dan 32 shell bash

有没有办法让 bash 脚本知道它是在前台还是后台运行,因此在每种情况下它的行为都会略有不同?

dev*_*ull 36

引用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
Run Code Online (Sandbox Code Playgroud)

所以你可以执行一个简单的检查:

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