< FrankJS />

Problem Solving: Adding the 'watch' command to MacOS

Linux has a a command called watch and it works like this:

watch is a command-line tool, part of the Linux procps and procps-ng packages, that runs the specified command repeatedly and displays the results on standard output so you can watch it change over time. By default, the command is run every two seconds, although this is adjustable with the -n secs argument.

This can be combined with utilities like df so that you have a "live monitor" of sorts that you can watch.

So I tried running this command with watch ps so I could view processes in the terminal window. Sadly, this did not work.

I thought to myself, how can i add this to my system?

I wanted to:

  1. Use a command called 'watch'

  2. Take an argument of a command with which we will apply the watch command to

  3. Have it behave like watch, every 2 seconds re-execute the passed argument (our command) and clear the console prior to each refresh

A quick cursory search revealed nothing regarding a MacOS port of the Linux tool. This left me with the solution of creating a script and ensuring it's a globally available command in my terminal environment.

So my two actionable tasks were to add a command to my environment and implement the logic for the command.

My MacOS uses zsh instead of the more commonly found bash shell. I am on Big Sur and with Catalina, Apple switched from bash to zsh.

This presented a challenge as there are differences in the shells and their syntax.

Here is the code I placed in my .zshrc file in my home directory:

function watch() {while :; do clear; $1; sleep 2; done} export -f watch

The first line, we create a function watch that we then fill with some logic.

Let's break this first line down. To begin, we are making a while loop that is always true, and then follow it with a set of commands to perform while this is true. We then clear the console to keep things nice and neat in between each refresh of watch. Next we have $1 which represents the first argument that we'll later pass into our function. sleep 2 provides a delay of 2 seconds between each refresh. Finally, we are done.

The second line we are exporting our watch, and since it's a function, we are using -f.

Finally, I can use watch ps!

Frank J Santaguida, 2022