user219882
user219882

Reputation: 15844

How to run a command in bash script which is not stopped when the script exits?

I have a BASH script which runs other commands and I would like to keep them running in case the main script stops. I tried to run those commands with & but it didn't help. Am I doing something wrong?

Upvotes: 3

Views: 2273

Answers (4)

Pavel Tankov
Pavel Tankov

Reputation: 449

Here is an example how to do this:

nohup your_command < /dev/null > output.log 2>&1 &

Upvotes: 2

fge
fge

Reputation: 121710

This is normal: the shell's job control mechanism terminates its jobs when it exits.

There are at least two solutions:

  • use disown after you have launched a job;
  • use at to schedule your job at a later time;
  • or use the nohup command.

Now, there is the question of what you want to do with the output of the command you launch in the background:

  • with disown, you lose it;
  • with at, stdout and stderr are sent to you by mail (but then you can redirect stdout/stderr if you want);
  • with nohup, you define the output file yourself.

Upvotes: 7

rahool
rahool

Reputation: 639

Try 'nohup' command to run COMMAND, ignoring hangup signals

nohup COMMAND &

Upvotes: 2

iniju
iniju

Reputation: 1094

Try using nohup (stands for no hangup) before your command:

nohup <your command>

It will forward the stdout of the command into a file called nohup.out by default.

Upvotes: 2

Related Questions