Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command every second in Bash?

Tags:

bash

loops

I want to write some image downloader and assign it on bash. What I have and what I need:

I have:

  1. Command, which works fine (something like wget http://mywebcam.com/image.jpg -O /var/cam/Image.jpg)
  2. Root rights

  3. Fast Internet line between my server and my webcam

What I need:

Download image from camera every second*(sleep 1?)* and rewrite it localy (my command do it well) Run this script at once and don't worry about restart (I think I need to create file with bash commands and run it once + set crontab work "on reboot" to this file, right?)

Maybe there's someone who knows what should I to do?

like image 837
Egor Sazanovich Avatar asked Feb 15 '12 19:02

Egor Sazanovich


People also ask

How do I run a Linux command every second?

Use watch Command Watch is a Linux command that allows you to execute a command or program periodically and also shows you output on the screen. This means that you will be able to see the program output in time. By default watch re-runs the command/program every 2 seconds.

What is repeat command in Linux?

There's a built-in Unix command repeat whose first argument is the number of times to repeat a command, where the command (with any arguments) is specified by the remaining arguments to repeat . For example, % repeat 100 echo "I will not automate this punishment." will echo the given string 100 times and then stop.

How do I run a Linux script every minute?

If you want to run a program or script in the background on Linux then cron job is very important. With the help of cron jobs, you can execute a program or script in the background after a given interval of time.

What is $1 and $2 in bash?

$1 is the first argument (filename1) $2 is the second argument (dir1)


2 Answers

If you want to run a command at one second intervals (one second between the end of one command and the beginning of the next, which is not the same as running every second), just do:

while sleep 1; do cmd; done 

If you want that to start on reboot, the method will depend on your system.

Note that it is certainly possible to start an execution every second rather than running at one second intervals, but I suspect that is not actually what you want. In addition, there are inherent risks with doing so. For example, if the system gets sluggish and the command starts taking longer than one second to run you may run out of resources.

like image 138
William Pursell Avatar answered Sep 18 '22 00:09

William Pursell


The command watch will do this for you straight up. It also displays the result in a nice way.

$ watch -n 1 date 

Substitute date for your command. The -n option specifies the interval in seconds.

like image 37
while Avatar answered Sep 17 '22 00:09

while