Jun 042011
 

tux-terminalSometimes is useful to run over and over again the same command until something happen, for example you could do a ls -lrt until a file has reached a certain dimension or is created, how to do it ?
Sure you can use bash history and use up arrow and return over and over again, or perhaps write some line of bash to get an infinite loop that run the same command, but there is a smarter approach to this : watch .


Watch

watch runs command repeatedly, displaying its output and errors. This allows you to watch the program output change over time. By default, the program is run every 2 seconds; use -n or –interval to specify a different interval. Normally, this interval is interpreted as the amout of time between the completion of one run of command and the beginning of the next run. However, with the -p or –precise option, you can make watch attempt to run command every interval seconds.

Basic usage

watch "qui il comando con le sue opzioni"

This will run your command with his options every 2 seconds

Options

The most common options for watch are:

-n set the interval in seconds.
-d flag will highlight the differences between successive updates.
-b option causes the command to beep if it has a non-zero exit.
-e cause watch to exit on an error from the program running.

Some examples

1) Display the content of a directory with differences highlighted

watch -d  "ls -alrt /tmp/

2) Display a clock on your terminal and update it every second:

watch -t -n 1 "date +%T|figlet"

Output

  ___   ___    ____  ____   _________
 / _  / _  _|___ | ___|_|___ /___ 
| | | | | | (_) __) |___ (_) |_  __) |
| |_| | |_| |_ / __/ ___) | ___) / __/
 ___/ ___/(_)_____|____(_)____/_____|

3) Monitor the queries being run by MySQL

watch -n 1 "mysqladmin --user=root --password=mypassword processlist"

4) Show the 10 processes that are consuming the most CPU:

watch 'ps -eo pcpu,pid,user,args | sort -k 1 -n -r | head -10'


Conclusions

Watch it’s a small shell command that like many Unix command just do 1 thing and do it well, repeats a command and shows his output.
But also “just” doing this it has helped me in many occasions and I hope that it can do the same with you.

Popular Posts:

Flattr this!

  2 Responses to “Watch – Run a command forever on the terminal”

  1. Very nice article. You want edit some of the formatting in the article, though. For example:

    watch -n 1 “mysqladmin –user= –password= processlist”

    WordPress is adding ending tags to and 😀

  2. Nice tip 🙂

Leave a Reply to Chen Xiao-Long Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*