73

I usually user watch linux utility to watch the output of a command repeatedly every n seconds, like in watch df -h /some_volume/

But I seem not to be able to use watch with a piped series of command like:

$ watch ls -ltr|tail -n 1

If I do that, watch is really watching ls -ltr and the output is being passed to tail -n 1 which doesn't output anything.

If I try this:

$ watch (ls -ltr|tail -n 1)

I get

$ watch: syntax error near unexpected token `ls'

And any of the following fails some reason or another:

$ watch <(ls -ltr|tail -n 1)

$ watch < <(ls -ltr|tail -n 1)

$ watch $(ls -ltr|tail -n 1)

$ watch `ls -ltr|tail -n 1)`

And finally if do this:

$ watch echo $(ls -ltr|tail -n 1)

I see no change in the output at the given interval because the command inside $() is run just once and the resulting output string is always printed ("watched") as a literal.

So, how do I make the watch command work with a piped chain of commands [other that putting them inside a script]?

  • 2
    run man watch and scroll down to examples... – don_crissti Oct 25 '16 at 17:57
126
watch 'command | othertool | yet-another-tool'
| improve this answer | |
  • 1
    Might be worth noting the generic approach as well watch sh -c 'command | etc' particularly looking at the approaches tried in the question. – sourcejedi Oct 25 '16 at 18:08
  • @sourcejedi I haven't really figured out why, but this won't always produce the same results. – Michael Mior Oct 16 '18 at 1:25
13
watch -n 1 "ls -lrt | tail -n20; date"

let's you pipe and run in a row.

| improve this answer | |
  • what is -n 1 for? – Nam G VU Mar 8 '19 at 4:50
  • 2
    @NamGVU: Run the command every 1 second – Duc Tran Mar 13 '19 at 18:46
2

If you would like to list all files in subdirectories too, you can use find command with exec option.

watch will update every 30 seconds and find will search for all *.log files in current dir (subdirs included) and will print filenames and their last 10 line:

watch -n30 'find . -name "*.log" -print -exec tail -n10 {} \; '
| improve this answer | |
0

Use a combination of single quotes (') and double quotes ("). For example:

watch -n 1 "links -dump 127.0.0.1/server-status | grep -e '\S' -Fe 'www.'"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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