1

So I have a bash script "example.sh" that will write into an output file, say "tmp_output.txt". (It will empty the file and rewrite if data already exists in it)

How can I use the watch command so that it will run "example.sh" every two seconds and view the changes being made in "tmp_output.txt"?

The watch command needs to used within the bash script.

closed as unclear what you're asking by l0b0, Michael Homer, Archemar, jimmij, Jenny D Feb 25 at 14:57

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What do you mean by "view the changes being made"? Do you want to print the new content in another terminal than where example.sh is running? – l0b0 Feb 23 at 5:45
1

watch by default runs the command through a shell, so if example.sh unconditionally writes to a file, you can have it run the script and then cat the output file:

watch 'example.sh; cat tmp_output.txt'

But of course, it might in general be more flexible to have the script just print to stdout, so you could view the output directly or redirect it to a file as desired.

The watch command needs to used within the bash script.

I'm not exactly sure what you mean by this. watch doesn't really lend itself that well to non-interactive use, given that it runs indefinitely and clears the screen during every execution etc. Also, running watch on a script from the script itself is a bit circular.

Of course you could do something similar just within the script:

while true; do 
    # do some work
    # write to tmp_output.txt etc.                      
    cat tmp_output.txt             # display it
    sleep 2                        # sleep and repeat
done
  • I thought as much, when I showed my professor that I was executing the script by doing "watch ./example.sh" he said that the watch command should be called within the script and not in the terminal. – Austin Feb 25 at 20:17
  • @Austin, well, that's education for you, sometimes you just learn that the way they teach things in school isn't actually the best one... Though of course it's possible that they have some odd sample solution for that, but if so, I'd like to see it. I just hope your grades aren't critically dependent on finding a solution to this. – ilkkachu Feb 25 at 20:56

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