Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

top command in shell script

I am trying to get first 5 lines of top command through expect script. Im calling this expect script from a shell script along with some other stuff.

top | head -5 gives me below output ie without cpu stats-

top - 09:10:58 up 46 days, 17:03, 12 users, load average: 0.01, 0.02, 0.00 Tasks: 138 total, 1 running, 137 sleeping, 0 stopped, 0 zombie

Mem: 16432400k total, 8408096k used, 8024304k free, 609200k buffers Swap: 6290736k total, 0k used, 6290736k free, 6754356k cached

If I run just top command on that remote server I can see there is a 2-3 second delay before the CPU states line is updated, can some one please help me to get all 5 lines with updated cpu states? Below is my expect script -

#!/usr/bin/expect -f
set user1 abc
set pass1 pass
set timeout 8
match_max 1000
spawn ssh -C -o stricthostkeychecking=no $user1@<ip>
expect "*?assword:*"
send  "$pass3\r"
expect "?xterm*"
send "\r"
send "top | head -5\r"
expect eof
like image 260
vinod_garag Avatar asked Apr 20 '26 00:04

vinod_garag


2 Answers

You need to run top in batch mode instead of the default interactive mode. In addition you need to define the number of iterations that top performs for getting its measurements.

num_iterations=3
top -b -n $num_iterations | head -5

If you want the output to only list the top 5 processes and skip the statistic header displayed, you can try this:

num_iterations=3
top -b -n $num_iterations | sed -n '8,12p'

Also tune the value of num_iterations as per your need.

like image 172
Tuxdude Avatar answered Apr 22 '26 17:04

Tuxdude


top -b -n 2 -u $(whoami) | grep -A6 -B5 PID |tail -12

Adjust below values as per requirement.

grep
-A$after_lines_count
-B$before_lines_count

tail -$($after+$before + 1)

tail value should be [ before lines count + after lines count + 1 (PID match line) ]

If you don't want user specific details.

  top -b -n 2 | grep -A6 -B5 PID |tail -12

Note: Number of top iterations are 2 (top -n 2) i.e, it takes 6 sec to display output ( depends on delay set per iteration)

like image 23
Shrikanth Y Avatar answered Apr 22 '26 17:04

Shrikanth Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!