How do I know if a bash script is running with nohup? How do I know if a bash script is running with nohup? shell shell

How do I know if a bash script is running with nohup?


Checking for file redirections is not robust, since nohup can be (and often is) used in scripts where stdin, stdout and/or stderr are already explicitly redirected.

Aside from these redirections, the only thing nohup does is ignore the SIGHUP signal (thanks to Blrfl for the link.)

So, really what we're asking for is a way to detect if SIGHUP is being ignored. In linux, the signal ignore mask is exposed in /proc/$PID/status, in the least-significant bit of the SigIgn hex string.

Provided we know the pid of the bash script we want to check, we can use egrep. Here I see if the current shell is ignoring SIGHUP (i.e. is "nohuppy"):

$ egrep -q "SigIgn:\s.{15}[13579bdf]" /proc/$$/status && echo nohuppy || echo normalnormal$ nohup bash -c 'egrep -q "SigIgn:\s.{15}[13579bdf]" /proc/$$/status && echo nohuppy || echo normal'; cat nohup.outnohup: ignoring input and appending output to `nohup.out'nohuppy


You could check if STDOUT is associated with a terminal:

[ -t 1 ]


You can either check if the parent pid is 1:

if [ $PPID -eq 1 ] ; then    echo "Parent pid=1  (runing via nohup)" else    echo "Parent pid<>1 (NOT running via nohup)"                                             fi

or if your script ignores the SIGHUP signal (see https://stackoverflow.com/a/35638712/1011025):

if egrep -q "SigIgn:\s.{15}[13579bdf]" /proc/$$/status ; then    echo "Ignores SIGHUP (runing via nohup)" else    echo "Doesn't ignore SIGHUP (NOT running via nohup)"                                             fi