Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a few cleanup commands to run for my datacaching scheme. I was thinking a bash script would be an easy way to check if the full clean up job needed to be run. But the cache is very time sensitive, so the check script needs to run every second. What's the best way to do this?

Crontab only goes down to minutes, which makes sense for most applications.

Can I install a bash script as a background service?

On second though, can I just start it with the & command and make it loop forever with a one second sleep?

I'm a newbie, would appreciate some advice.

share|improve this question
up vote 9 down vote accepted

The simplest way is watch command. You pass number of seconds to -n option:

 watch -n1 'rand'
share|improve this answer
interesting way to do it. I've never heard of watch. What if the scrip takes longer than a second to execute? – Beachhouse Jan 9 '13 at 19:04
According to manpage: "Normally, this interval is interpreted as the amout of time between the completion of one run of command and the beginning of the next run. However, with the -p or --precise option, you can make watch attempt to run command every interval seconds." So it should do fine. – Nykakin Jan 9 '13 at 19:17
is 'rand' the name of the script? so I would execute: & watch -n1 'mem.sh' – Beachhouse Jan 9 '13 at 19:20
rand is command returning random number. Since you want to execute script you have to set up PATH variable or pass a path like $ watch -n1 './test.sh' – Nykakin Jan 9 '13 at 19:27
If you want it to run in the background even if you leave the terminal you could try nohup watch -n5 'bash script.sh' & – jamietelin Aug 5 '15 at 20:10

use sleep . try this while true ; do ./your-script & ; sleep 1; done

share|improve this answer
ok, let me edit it and I'll post the full script in a bit. – Beachhouse Jan 9 '13 at 17:13
Where would I put the 'while true ; do ./your-script & ; sleep 1;' done? – Beachhouse Jan 9 '13 at 17:14
put it in another script and run it as background process – harish.venkat Jan 9 '13 at 17:19
why have two scripts? – Beachhouse Jan 9 '13 at 17:20
@Beachhouse you can run it by itself or you can put that into a startup script so it starts when the box comes up. – h3rrmiller Jan 9 '13 at 17:20

I am using something like that:

sleep 1; // wait one second till next run
./script-name &; // run same script again on background

But I don't know if it is correct :)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.