How can I run `watch` as a background job?
The purpose of watch
is to show the results of a command full-screen and update continuously; if you're redirecting the output into a file and backgrounding it there's really no reason to use watch in the first place.
If you want to just run a command over and over again with a delay (watch
waits two seconds by default), you can use something like this:
while true; do
cmd >> output.txt
sleep 2
done
Update, thanks to @SDK:
watch -n 1 'date | tee -a output.txt' &>/dev/null &
tee is incredibly useful and will push the output to the file specified.
Previous Answer:
Here's a way:
watch -n 1 'date' &>/dev/null &
Since you background the process, we can assume you don't need the terminal display and you are fine redirecting to a file. If you do that you will be able to background watch
without issue.
sleep
, as suggested by Michael Mrozek, will slowly lag which can be undesirable. Aside from a convoluted shell script that monitors system time and executes a command based upon elapsed time, watch -p
can be a good option for precise timings.
For precise timings:
watch -n 1 -p 'date' &>/dev/null &
I'm not sure about your motivations, but maybe this would be enough?
while true; do sleep 2; cmd >>output.txt; done &
Otherwise, please explain why you really need watch
.