Running linux command periodically

Sometimes we need to monitor something in our servers like memory usage or hard drive space during a deployment process that is failing or a program that it´s filling all our memory and this implies to run a command in our consoles more than once to see the changes along the time.

A very useful command in this situations is watch. This command allows us to execute periodically a given command. For example, imagine that we want to visualize our memory. Without the watch command, we should execute the free command a lot of times one after the other. But with the watch command we can do this:

watch -n 2 --differences free
  • -n: Interval of seconds.
  • –differences: Highlight the difference between updates.

Executing this line the free command will be executed each two seconds and, in addition, the differences between the updates will be highlighted.

Unfortunately, for OS X users, there are bad news, this command is not available in the Terminal. But, we can solve it with a simple shell script.

#!/bin/bash
# usage: watch.sh <your_command> <sleep_duration>

while :; 
  do 
  clear; 
  echo "$(date)"
  $1; 
  sleep $2; 
done

It´s not perfect because you cannot execute command with parameters but, at least, you can have something similar to execute for example the memory_pressure command. Because, another bad news, the free command is not available in OS X systems.

See you.

Advertisements
Running linux command periodically

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s