Issue
Ive got a script that takes a quite a long time to run, as it has to handle many thousands of files. I want to make this script as fool proof as possible. To this end, I want to check if the user ran the script using nohup and '&'. E.x.
me@myHost:/home/me/bin $ nohup doAlotOfStuff.sh &
. I want to make 100% sure the script was run with nohup and '&', because its a very painful recovery process if the script dies in the middle for whatever reason.
How can I check those two key paramaters inside the script itself? and if they are missing, how can I stop the script before it gets any farther, and complain to the user that they ran the script wrong? Better yet, is there way I can force the script to run in nohup &?
Edit: the server enviornment is AIX 7.1
Solution
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 by user elsewhere 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 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
. I left it there just in case you choose to remove the exec
line.
Answered By - alvits