How to find out if a bash script works with nohup?

I have a script for processing entries in some files, it usually takes 1-2 hours. When it works, it prints the progress of the processed records.

Now, what I want to do: when he works with nohup, I do not want him to print progress; it should print progress only when it starts manually.

My question is: how do I know if a bash script is working with nohup?

Assume a team nohup myscript.sh &. In a script, how do I get nohupfrom the command line? I tried to use $0, but it gives myscript.sh.

+8
source share
5 answers

You can check if STDOUT is connected to the terminal:

[ -t 1 ]
+1
source

, nohup ( ) , stdin, stdout / stderr .

, , nohup, SIGHUP ( Blrfl ).

, , , , SIGHUP. Linux /proc/$PID/status, SigIgn SigIgn.

pid bash, , egrep. , SIGHUP (.. is nohuppy):

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

, , - readlink on /proc/$$/fd/1 , nohup.out.

, pts0:

#!/bin/bash

readlink /proc/$$/fd/1

if [[ $(readlink /proc/$$/fd/1) =~ nohup.out$ ]]; then
    echo "Running under hup" >> /dev/pts/0
fi

But the traditional approach to such problems is to check whether the output is a terminal:

[ -t 1 ]
+1
source

Thanks guys. Checking STDOUT is a good idea. I just find another way to do this. That is to check tty. test tty -s check its return code. If it is 0, then it works on the terminal; if it is 1, then it works with nohup.

0
source

You can 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 fooobar.com/questions/1147436 / ... ):

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
0
source

All Articles