1

I'm currently executing the following:

watch -n 100 'sh script.sh >> /path/to/output/output.txt' &

It's been running for 30 minutes (I can verify with ps -ef | grep watch), however there's nothing being written to /path/to/output/output.txt (the file doesn't exist). script.sh executes commands that prints to terminal, so shouldn't the >> be directing everything to output.txt?

  • Not really sure what the meta conversation is in the other comments, but this seems relevant https://unix.stackexchange.com/a/145433/40482 – bxm Apr 15 '23 at 14:47
  • @bxm Thanks, that answer by Michael helps. I'm going to use that instead of watch – student010101 Apr 15 '23 at 14:51

1 Answers1

1

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 > … &