Running a program / script forever (and in the background) [Linux]

This article will teach you how to create a looped command in linux, that will run permanently in the background. The only requirement for this is that you are able to enter commands into a linux terminal.

Create your file

  1. Create an empty file called loop.sh with `touch loop.sh`
  2. Begin editing the empty file - `nano loop.sh`
  3. Enter the contents of below, replacing the very obvious `mycommandhere` with your command. Any other commands you might need to run afterwards can be placed on the next line.

    #!/bin/bash
    while true
    do
        mycommandhere
        sleep 1
    done​
  4. Run it once with `bash loop.sh`. If that doesn't work, you might have to directly use `/bin/bash loop.sh`
  5. If you don't need an easy way to stop or restart it, you can send it off to the background with `/bin/bash/loop.sh &>/dev/null &`. This is an extremely carefree way of handling it, so be careful with running this.

With the above approach, there's a limited amount of ways that it can be terminated. There are much more elegant and preferrable solutions that might fit your use case better:

  • Use a terminal multiplexer, such as Tmux or Screen
  • Run the program as a service, using Systemd or PM2
  • linux, setup, friendly
  • 2 Users Found This Useful
Was this answer helpful?

Related Articles

Running a program as a service [Windows]

In this article, we'll be describing how you can turn any Windows program into an auto-restarting...

Installing Python [Windows/Linux]

The following steps detail how you can install Python on a Windows or Linux machine. Python...

Scheduling commands with crontab [Linux]

If you need to schedule a command to be run at a certain frequency, you may be able to use...