Hypothesis
Your watch
is stopped. It was stopped before it could launch a shell that would interpret sh script.sh >> /path/to/output/output.txt
. The redirection has not happened yet, this is why the file does not exist. sh script.sh
has not been started yet.
Verification
Your interactive shell may have told you the job was stopped; maybe you missed the message. Invoke jobs
and you should see your watch
is Stopped
.
Explanation
The reason watch
is stopped is it got SIGTTOU. SIGTTIN and SIGTTOU are signals that (by default) stop background processes (i.e. processes not in the foreground process group) that try to read from or (respectively) write to the terminal. Usually the terminal is configured not to send SIGTTOU to background processes that try to write (therefore e.g. date &
works), but if a background process tries to configure the terminal then it will get SIGTTOU anyway. The whole mechanics prevents background processes from stealing input from or tampering with the terminal.
It so happens watch
tries to configure the terminal quite early. If you run watch
in the background (watch … &
like you did) then it will receive SIGTTOU and get stopped. If you try to bg
it, it will be stopped again. If you try to fg
it then it will be put in the foreground, it will be allowed to interact with the terminal, it won't get SIGTTOU and it will work.
Conclusion
watch
is not meant to be run in the background.
Working alternative
Use a simple loop:
while sleep 100; do … done > … &
watch
– student010101 Apr 15 '23 at 14:51