Running Bash Script in Background Continuously Without Terminal Control

Hello,

I've created a bash script that retrieves the IP of the device connecting to my lan4 port and then sends it to the port-mirroring configuration file.

The issue I'm facing is that I'd like my script to always run in the background and not take control of the terminal. I've tried various techniques with rc.local but nothing seems to work...

Do you have any advice to offer?

Thank you for your response!

/path/to/script &

3 Likes

It works well to launch it only once, and it doesn't take control of the terminal.

However, what I would like is for the program to always run in the background so that it can retrieve the IP address every time someone connects to the port.

A snippet from a script which is checking every 5 sec, you start the script with the control operator & as already pointed out, the shell executes the command in the background in a subshell and then the script keeps on running and checking every X seconds:

SLEEP=5
while sleep $SLEEP; do
    do-what-you-want
done

hotplug script?

This is only one half of the real solution. The /path/to/script & sends it to background, but it is still bound to the terminal. If you exit/kill the terminal the background job is gone, too.

In order to prevent this behaviour you have to submit
disown <pid_of_the_background_job>
on the command line. man bash is your friend

Then you can exit/kill the terminal and your background job goes on for ever - until you expicitly terminate/kill it.

That's not enough, see my reply to @AndrewZ

Have you tried it?

Note this is ash and not bash

A shell script in a tight sleep loop seems like the wrong way to tackle the problem given the OP, sucking cycles unnecessarily. IMO the event should trigger the IP retrieval and then the script is dusted and done.

My understanding that OP needs this run on startup:

so in this case the background process is pretty safe

1 Like

Yes, both success and failure.

The OP asked for a bash solution, not an ash solution. Or did I miss something?

Bash is not the standard shell in OpenWRT and if the user is asking these question it is safe to assume he is not an expert and is using the standard ash shell.
Bash is often used as a moniker for the shell.
But of course the OP can only give the definitive answer.

Ash is lacking in some things disown is one of those

You're making a lot of assumptions:

  • the user is not an expert
  • the user is using the standard ash shell
  • Bash is often used as a moniker for the shell

I think it's better at first to take the OP's topic in the literal sense of the word: when he's talking of a bash script, then I assume he already has bash installed; otherwise a bash script won't run at all.

Fully agreed.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.