Running a command (script, program, et cetera) on a regularly timed interval can
be accomplished a few different ways. One way, is to leverage the crontab
utility, which schedules runs to run one or more times per day.
While a fantastic utility, crontab
can be a bit heavy at times, especially if
you just need to run something for a finite amount of time.
In those types of scenarios, you can use the watch
command, which works the
same way that crontab
does, but right from your command-line.
Let’s say you want to check the contents of a directory every 5 seconds, you can
run the following:
watch --interval 5 ls
Or more concisely:
watch -n 5 ls
Once you’re done monitoring things, you can simply hit Ctrl+C
and watch
will
cease execution!
To take things a bit further, watch
also has an argument that will tell it to
highlight the differences between runs:
# Highlight the differences
watch -n 5 --differences ls -al
# Also, highlight the differences
watch -n 5 -d ls -al
# Highlight the differences, persisting the highlight between runs
watch -n 5 --differences=permanent ls -al