How to Include Nohup Inside a Bash Script?

How to Include Nohup Inside a Bash Script?

I have a large script called mandacalc which I want to always run with the nohup command. If I call it from the command line as:

nohup mandacalc &

everything runs swiftly. But, if I try to include nohup inside my command, so I don't need to type it everytime I execute it, I get an error message.

So far I tried these options:

nohup (
command1
....
commandn
exit 0
)

and also:

nohup bash -c "
command1
....
commandn
exit 0
" # and also with single quotes.

So far I only get error messages complaining about the implementation of the nohup command, or about other quotes used inside the script.

cheers.

1

5 Answers

Try putting this at the beginning of your script:

#!/bin/bash

case "$1" in
    -d|--daemon)
        $0 < /dev/null &> /dev/null & disown
        exit 0
        ;;
    *)
        ;;
esac

# do stuff here

If you now start your script with --daemon as an argument, it will restart itself detached from your current shell.

You can still run your script "in the foreground" by starting it without this option.

1

Just put trap '' HUP on the beggining of your script.

Also if it creates child process someCommand& you will have to change them to nohup someCommand& to work properly... I have been researching this for a long time and only the combination of these two (the trap and nohup) works on my specific script where xterm closes too fast.

1

Create an alias of the same name in your bash (or preferred shell) startup file:

alias mandacalc="nohup mandacalc &"

Why don't you just make a script containing nohup ./original_script ?

There is a nice answer here:

#!/bin/bash

### make sure that the script is called with `nohup nice ...`
if [ "$1" != "calling_myself" ]
then
    # this script has *not* been called recursively by itself
    datestamp=$(date +%F | tr -d -)
    nohup_out=nohup-$datestamp.out
    nohup nice "$0" "calling_myself" "$@" > $nohup_out &
    sleep 1
    tail -f $nohup_out
    exit
else
    # this script has been called recursively by itself
    shift # remove the termination condition flag in $1
fi

### the rest of the script goes here
. . . . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.