inbuilt nohup logic into the script

Hi All,

I know one way to use nohup as below:

nohup myscript.ksh

However, just wanted to know is there any way to write the nohup logic directly into the script so that we can execute the script without need to specify the nohup like this:

myscript.ksh

Many Thanks in advance.

This might do what you want:

mynohup(){
# Close stdin, and make any read attempt an error
    if [ -t 0 ]
    then
        exec 0>/dev/null
    fi

# Redirect stdout to a file if it's a TTY
    if [ -t 1 ]
    then
        exec 1>nohup.out
        if [ $? -ne 0 ]
        then
            exec 1>$HOME/nohup.out
        fi
    fi

# Redirect stderr to stdout if it's a TTY
    if [ -t 2 ]
    then
        exec 2>&1
    fi

# Trap the HUP signal to ignore it
    trap : HUP
}

Save it in a file, source that in any script you want to ignore SIGHUP in, call the mynohup function (or whatever you want to call it) once, and you're good to go. Tested with ksh and bash, and modeled after the nohup shipped with the GNU coreutils.

Thanks for the reply Pludi. I have implemented the solution.

I found this thing very useful. Thanks for the info.
just one query, is there any side effects if someone executes the script explicitly with nohup having this logic inside the script.

Haven't explicitly tested it, but there shouldn't. After all, the external nohup utility should make sure that the default FDs aren't connected to a terminal anymore, and that SIGHUP is ignored.

i have just tried but i think its not working with external nohup command alongwith.

. nohup_file
mynohup

while :
do
echo running
sleep 1
done

when I run this, normally (without external nohup) its working fine and the stdout has been appending in the nohup.out as expected.

but when I run this with,

nohup ./script.ksh &

nothing happens. nohup.out file is zero size.

Is there any way ( some checks ) so that we can detect the external nohup and ignore anyone of that (external or internal). so that it works in all cases..
or any other solution to make it generic.

the reason for asking this is even if I put the logic inside the script and some people may unaware of that and may execute the script with external nohup.

thanks.

What platform are you on? Because I couldn't confirm that behavior, neither on Linux nor HP-UX, neither with bash nor ksh.

I am on HP-UX

HP-UX B.11.11 U 9000/800 914153510