A technical troubleshooting blog about Oracle with other Databases & Cloud Technologies.

How To tell if a script was run in the background ?

1 min read
The ps utility can get the process state. The process state code will contain the character + when running in foreground. Absence of + means code is running in background.

However, it will be hard to tell whether the background script was invoked using nohup. It's also almost impossible to rely on the presence of nohup.out as output can be redirected elsewhere by the user at will.

There are 2 ways to accomplish what you want to do. Either bail out and warn the user or automatically restart the script in the background.
#!/bin/bash
local mypid=$$
if [[ $(ps -o stat= -p $mypid) =~ "+" ]]; then
echo Running in foreground.
exec nohup $0 "$@" &
exit
fi
# the rest of the script
...
In this code, if the process has a state code +, it will print a warning then restart the process in background. If the process was started in the background, it will just proceed to the rest of the code.

If you prefer to bailout and just warn the user, you can remove the exec line. Note that the exit is not needed after exec. It is left there just in case you choose to remove the exec line.