10

How can I write a shell script that shows the results in real time?

Something like the top command that updates the results after some fixed intervals of time.

alt text

1
  • 6
    probably using a curses interface... but I think this is more heavily a programming question and belongs on SO Commented Aug 28, 2010 at 17:21

5 Answers 5

13

you can use the watch(1) command to run your script at regular intervals:

watch -n 1 myscript.sh

This will run myscript.sh every 1 second clearing the screen between each run and with a timestamp in the corner. You can use the -d option and it will even highlight differences in the output per run.

2
  • I was just thinking of how to answer it using watch. Commented Aug 30, 2010 at 2:51
  • I don't have watch. Could you be more specific? What OS? Commented Jun 25, 2012 at 6:10
7

It would help if you were a lot more specific about what you are trying to do.

Here is an extremely simplistic example:

while true
do
    clear
    date
    sleep 1
done
2

Most of that data is generally exposed in the /proc virtual file-system primitives. Each process has an entry in /proc in a directory called the PID. So /proc/5437 would have the primitives for the 5437 process. Reading the primitives there and parsing appropriately would yet you close to what top does.

Top actually works by calling specific function calls that extract this information directly from the kernel instead of pulling it from files. To do the same from bash you'd have to either pull it from the /proc virtual file system, or extract it out of other calls such as to ps.

As for real-time, that isn't quite doable at the level of detail top provides. You can slice time fine enough that it appears to be real-time, but you will still be getting time-slices.

2

Erm, in case you're looking at top output for a longer time, and not just to check if a program is doing fine, I suggest using htop.

It give's you a lot of real time information and is easier to control and manage.

You can change the layout of the output, such as bar graphs and columns.

1
  • I believe he is asking how to write an app that polls at regular intervals not about top or htop specifically. Commented Aug 30, 2010 at 10:18
1

top uses Curses and reads the /proc file system

1
  • 1
    Except on systems that don't have /proc. Another way to get the information is sysctl(8)/sysctl(3). Commented Jun 25, 2012 at 6:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.