Eran Levi
Eran Levi

Reputation: 363

linux shell script: how can I create a service that will run in background?

I have a simple question, i searched and I couldn't find a solution.

I have a simple shell script that run a small php code every 2 seconds, I wrote it and save as a file:

$ cat every-2-seconds.sh
#!/bin/bash
while true
do
php /home/account/domains/domain.co.il/public_html/my-php-script.php
 sleep 2
done

Now, i need that this script will always run on background, but I also need that it will run on startup, Just like a service, it should always run in background, and I never want to start it manually (of course, if something happen and it will stop, i should be able to start it manually) I heard about nohup, but its not a service right? and I can start it on startup.. :(

Can you help me on this??

Upvotes: 0

Views: 252

Answers (1)

Andy
Andy

Reputation: 50550

You can make your script run with this line of code (assuming you are in the directory with your script)

nohup every-2-seconds.sh &

The & will run this as a background task and nohup will keep the process running even after you've disconnected from your session.

To handle starting it on reboot you need to add this command to your crontab

crontab -e
@reboot /path/to/every-2-seconds.sh > /dev/null

In the crontab you need to specify the full path. You can change /dev/null to the file you want output to go to (assuming you want the output)

Upvotes: 1

Related Questions