Shell Script – How to Perform the Watch Command with Pipes?

command linepipeshell-scriptwatch

I learned today the wonderful shuf command:

ls | shuf  

shows me a listing of the working direcotry, but thanks to shuf each time I execute this piped command expression with another order.

So I thought, why not repeat this expression every second anew, and so I tried

watch -n1 ls | shuf          (and got no output)
watch -n1 (ls | shuf)        (and got an error)
watch -n1 {ls | shuf}        (and got an error)

then I put ls | shuf into its own file and made a script foo out of it.

watch -n1 ./foo               (this times it worked)

Is it possible to apply the watch command onto a piped command expression without having the expression be made into a script file ?

Best Answer

There exists several variants of a watch command, some that spawn a shell to interpret a command line made of the concatenation of the arguments passed to watch (with space characters in between). In those you can do:

watch 'ls | shuf'

same as:

watch ls '|' shuf

(those watch actually run: "/bin/sh", ["sh", "-c", "ls | shuf"] and are quite dangerous in that that second level of interpretation can open the door to bugs and security issues when not anticipated, procps-ng's watch can avoid that behaviour with the -x option).

And there are those that just execute the command whose name is given in the first argument with all the arguments as arguments. In those:

watch sh -c 'ls | shuf'
Related Question