When I run:
watch 'cmd >> output.txt' &
the job gets suspended by the system:
3569 Stopped (tty output)
Is there a workaround?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
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 &
Depends on your motivations:
You want to run something periodically. Then you could use directly cron. (If a time granularity of 1 minute is enough for your purposes).
You want to just run something repeatedly:
while sleep 2 ; do cmd done >& log.txt
(You can run this from the crontab for example, although using a script is highly recommended).
You want to run periodically a command and have access to the output of its last execution.
You can write the output to a ramfs (modifying the script before):
while sleep 2 ; do cmd >& last_execution.log done
or even better:
while sleep 2 ; do cmd >& last_execution.log.tmp mv last_execution.log.tmp last_execution.log ## atomically done
You can combine
watch, so that you can always check the latest status, as long as it fits in one screenful:
screen watch -n 3660 ./make-backup.sh
You can use screen command.
so, this works
watch -tg 'grep Hello ./helloWorldOut.txt' >/dev/null
as in not clearing the screen and returning your cursor when it is complete - but it also calls into question why you are using watch. The command is designed to be visual, so you can't miss it. Perhaps your need is not what they created this command for. Just open a second terminal session (you should have two open anyway,) and run either the watch command you need or a quick cli while loop to do what you need, but running it as a bg job is really pushing it (what the command is there for) all the way to the side...