Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a bash command run periodically?

Tags:

bash

I want to execute a script and have it run a command every x minutes.

Also any general advice on any resources for learning bash scripting could be really cool. I use Linux for my personal development work, so bash scripts are not totally foreign to me, I just haven't written any of my own from scratch.

like image 881
jerome Avatar asked Jun 30 '13 20:06

jerome


People also ask

How do you run a periodically in a shell script?

Run a Linux Command Every One Minute To specify the time interval for a periodic run, use the -n option. For example, to run a Linux command or program every 1-minute use the following command. This will obviously run the 'ps -ef' command every 1 minute.

How do I make a script run automatically?

On Windows, the simplest way of running a program at startup is to place an executable file in the Startup folder. All the programs that are in this folder will be executed automatically when the computer opens. You can open this folder more easily by pressing WINDOWS KEY + R and then copying this text shell:startup .

How do I run a command multiple times in bash?

How To Run a Command Multiple Times in Bash. Wrap your statement for i in {1..n}; do someCommand; done , where n is a positive number and someCommand is any command. To access the variable (I use i but you can name it differently), you need to wrap it like this: ${i} . Execute the statement by pressing the Enter key.


2 Answers

If you want to run a command periodically, there's 3 ways :

  • using the crontab command ex. * * * * * command (run every minutes)
  • using a loop like : while true; do ./my_script.sh; sleep 60; done (not precise)
  • using systemd timer

See cron

Some pointers for best bash scripting practices :

http://mywiki.wooledge.org/BashFAQ
Guide: http://mywiki.wooledge.org/BashGuide
ref: http://www.gnu.org/software/bash/manual/bash.html
http://wiki.bash-hackers.org/
USE MORE QUOTES!: http://www.grymoire.com/Unix/Quote.html
Scripts and more: http://www.shelldorado.com/

like image 172
Gilles Quenot Avatar answered Sep 22 '22 01:09

Gilles Quenot


In addition to @sputnick's answer, there is also watch. From the man page:

Execute a program periodically, showing output full screen 

By default this is every 2 seconds. watch is useful for tailing logs, for example.

like image 43
Yossarian Avatar answered Sep 22 '22 01:09

Yossarian