2

It is possible to do something like this:

nohup ./run.sh > /dev/null 2>&1 &

Which sends the process to background, discards its output and allows us to close terminal.

Is there any possible way to do that using the script itself? I mean, I would execute this:

./run.sh

and somewhere inside the script, can we do something like this:

nohup "$0" > /dev/null 2>&1 &

So that when the script is run, it will act same as above?

I suppose we can have two separate scripts for this. However, is it possible to do in a single script?

I'm asking because the script will be called from the system, and I don't want to change how the system calls the script, I'd prefer I change how the script is executed.

2

You can implement this if you have something to decide if the script should execute itself in the background or if it already is the one in the background, e.g. a command line argument.

Assuming you normally call your script

./run.sh

you could add a command line argument, e.g. bg to tell the script that it already is in the second execution, so it will recursively call itself endless times (or until the system resources have been used up).

./run.sh bg

You can implement it like this

#! /bin/sh

if [ "$1" = "bg" ]
then

    # do the normal work

else

    nohup "$0" bg > /dev/null 2>&1 &

fi
  • Great, that works for me! – Maximus May 10 at 9:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.