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 ?


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'
  • when I am in a shell and execute "sh -c" does it mean I start another shell in this shell ? – Abdul Al Hazred Mar 29 '15 at 22:16
  • sh -c 'a command line' is itself a shell command line that is interpreted by your interactive shell and tell it to run a shell to interpret the other command line passed in that 3rd argument. – Stéphane Chazelas Mar 29 '15 at 22:19

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.