How to save unix top command output to a variable?

I need to save the output of the top command to a variable, and I do this:

myvar=`top -b -n1 | head -n 18` 

The problem is that it ignores the returned characters, so when I repeat the contents of $myvar , I see something like:

top - 15:15:38 up 745 days, 15:08, 5 users, load average: 0.22, 0.27, 0.32 Tasks: 133 total, 1 running, 132 sleeping, 0 stopped, 0 zombie Cpu(s): 6.4% us, 1.6%sy, 0.0% ni, 91.7% id, 0.3% wa, 0.0% hi, 0.0% si Mem: 2074716k total, 2038716k used, 36000k free, 84668k buffers Swap: 4192924k total, 107268k used, 4085656k etc...

How to save all the top data?

+4
source share
3 answers

Note the difference:

 #! /bin/bash x=`top -b -n 1 | head -n 5` echo $x echo -------------------- echo "$x" 

Output:

  top - 14:33:09 up 7 days, 5:58, 4 users, load average: 0.00, 0.00, 0.09 Tasks: 253 total, 2 running, 251 sleeping, 0 stopped, 0 zombie Cpu (s): 1.6% us , 0.4% sy, 70.3% ni, 27.6% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st Mem: 3926784k total, 3644624k used, 282160k free, 232696k buffers Swap: 9936160k total, 101156k used, 9835004k free, 1287352k cached
 --------------------
 top - 14:33:09 up 7 days, 5:58, 4 users, load average: 0.00, 0.00, 0.09
 Tasks: 253 total, 2 running, 251 sleeping, 0 stopped, 0 zombie
 Cpu (s): 1.6% us, 0.4% sy, 70.3% ni, 27.6% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
 Mem: 3926784k total, 3644624k used, 282160k free, 232696k buffers
 Swap: 9936160k total, 101156k used, 9835004k free, 1287352k cached 

Without quotes, the contents of the variable are based on the processing of shell arguments.

+16
source

If you are looking for a certain piece of information in the top release, I would tend to filter the top output for what you are looking for before storing it, rather than capturing everything and then extracting what you need.

+1
source

You can pass it through sed to catch and convert line breaks, for example.

 top -n1 | sed 's/\(.*\)$/\1__CUSTOM_LINE_MARKER/g' 

prints CUSTOM_LINE_MARKER after each line. although Rob Wells answer above is probably the best approach.

-one
source

Source: https://habr.com/ru/post/1299475/


All Articles