How to use “watch” on Mac OSX

In case you are looking for a “watch” command, similar to Linux, for your Mac OSX platform. You can create a shell script which can be used to emulate the similar requirement of what a watch command does on Linux.

Create a shell script named “watch” on your path “~username/bin/”, with the following content:

#!/bin/sh

if [ -z "$2" ]; then
echo "Usage: $0 seconds command" >&2
exit 1
fi

seconds=$1
shift 1

while sleep $seconds; do
clear
echo "Press ctrl+c to quit\n";
$*
done

Once this file is created, provide execute grants.
shell> chmod +x ~username/bin/watch

Try running a sample command as given below.
shell>watch 3 "ls -lF $HOME"

See the results reload every 3 seconds in this example. This is a work around for the linux watch command. Notice the delay before running the command too.
In case you are unable to run the watch command as explained above, kindly refer the below steps to add the “watch” command to your self executable bin path.

Once you added your custom created binaries/shell scripts to your “~username/bin” path, you need to add them to the $PATH to make them run as an executable command. Check whether “~username/bin/” is already in the $PATH
shell> echo $PATH

If not in the $PATH, add the ~username/bin path to $PATH using the below command.
shell> export PATH="$PATH:/Users/username/bin/"

Once added, verify it again.
shell> echo $PATH

If you want this command added everytime you login. Add the command on the .bashrc or .bash_profile file under the user home directory.
Add this command in the .bash_profile or .bashrc file
export PATH="$PATH:/Users/username/bin/"
Now your shell script can run as a built-in command on shell.

Leave a Comment

Read previous post:
How to clear DNS cache in Mac OSX

Every outgoing DNS request is cached for optimized performance. Its good for faster lookups of the same host but sometimes...

Close