Saturday, March 1, 2014

OSX analog of the *nix 'watch' utility

OSX does not have a watch utility. Yes, it can be easily simulated using the while loop:

while true; do ls -l logfile.txt; sleep 5; done

I found that having a function for that purpose in the .bash_profile is more convenient. Additionally it timestamps new and weeds out repetitive output. Adjust to your taste:

function lg(){
  prev=""
  while true
  do
    curr="$($* 2>&1)"
    if [ "${prev}" != "${curr}" ]
    then
      echo $(date +"%H:%M:%S"):
      echo "${curr}"
      prev="${curr}"
    fi
    sleep 5
  done
}

Here is an example use with output:

$ lg "ls -AFGhlO log_*"
20:05:52:
-rw-r-----  1 vlad  staff  -    0B Mar  1 20:00 log_2013.zip
-rw-r-----  1 vlad  staff  -    0B Mar  1 20:00 log_2014.zip
20:06:27:
-rw-r-----  1 vlad  staff  -    0B Mar  1 20:00 log_2014.zip
20:06:32:
ls: log_*: No such file or directory
20:06:47:
-rw-r-----  1 vlad  staff  -    0B Mar  1 20:06 log_2015.zip
^C
$ 

Note, that the parameter command needs to be quoted or escaped properly to execute correctly.

read more ...