1

I want to execute the top command from my bash script

the problem is that usually when I type the top command on the console , I exit by Ctrl+C.

but how to exit from top when I run the top command from my bash script ?

for example how to print the free memory from top in bash ?

I do the following but command not return value as I am explained

 top | grep Mem: | awk '{print $6" "$7}'

when I run the top from the console:

  top

  top - 17:55:24 up 20 days,  8:05,  3 users,  load average: 0.08, 0.08, 0.04
  Tasks:  93 total,   1 running,  92 sleeping,   0 stopped,   0 zombie
  Cpu(s):  1.0%us,  3.2%sy,  0.0%ni, 95.2%id,  0.5%wa,  0.0%hi,  0.0%si,  0.0%st
  Mem:   2075516k total,  1731156k used,   344360k free,   373308k buffers
  Swap:  4192924k total,       76k used,  4192848k free,  1130448k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+       COMMAND                                                               
   1 root      15   0  2072  656  568 S  0.0  0.0   0:01.36 init     
 .
 .
 .
5
  • 1
    what about using the "free" command, instead of top?
    – spider
    Commented Sep 22, 2014 at 15:03
  • I dont have free command on my linux box machine - sorry Commented Sep 22, 2014 at 15:09
  • 2
    top -n1 will run just one iteration.
    – JRFerguson
    Commented Sep 22, 2014 at 15:12
  • 1
    you can get the some of the info using vmstat command or looking directly into /proc/meminfo. What exactly do you want to achieve?
    – spider
    Commented Sep 22, 2014 at 15:13
  • top -bn1 will be helpful.
    – Ramesh
    Commented Sep 22, 2014 at 15:13

2 Answers 2

2

@jimmij's answer is good from the top options point of view, though it looks like the format of the output from top can't be relied upon in a portable manner.

You mention you don't have the free utility, but this is just a wrapper around the /proc/meminfo interface, which you almost certainly do have. Why not just get the information you need directly from the horses mouth (the kernel):

$ grep MemFree: /proc/meminfo
MemFree:           75916 kB
$ 

Or if you want it formatted as a single number by awk:

$ awk '$1=="MemFree:" {print $2}' < /proc/meminfo
74320
$ 
1

Try this:

top -bn1 | awk '$1=="Mem:" {print $6" "$7}'
2
  • Doesn't work for me on Ubuntu 14.04, because the relevant line in the top output starts with KiB Mem: and so all positional params would need to be incremented. Commented Sep 22, 2014 at 18:05
  • This solution is strictly designed for OP question and his output of top. In your top version (BTW and mine too) just change it a little bit: top -bn1 | awk '$2=="Mem:" {print $6" "$7}'. You may need to change column numbers as well.
    – jimmij
    Commented Sep 22, 2014 at 18:08

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.