How to correctly save the unix top command output into a variable? How to correctly save the unix top command output into a variable? unix unix

How to correctly save the unix top command output into a variable?


Notice the difference:

#! /bin/bashx=`top -b -n 1 | head -n 5`echo $xecho --------------------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.09Tasks: 253 total,   2 running, 251 sleeping,   0 stopped,   0 zombieCpu(s):  1.6%us,  0.4%sy, 70.3%ni, 27.6%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%stMem:   3926784k total,  3644624k used,   282160k free,   232696k buffersSwap:  9936160k total,   101156k used,  9835004k free,  1287352k cached

Without the quotes, the contents of the variable are ground up in the shell's argument processing.


If you are looking for a particular piece of info within the top output i'd be inclined to filter the top output for what you're looking for before storing it rather than capture everything and then extract what you need.


You could pipe it out through sed to catch and transform the line breaks, e.g.

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

will output the CUSTOM_LINE_MARKER after every line. though Rob Wells answer above is probably a better approach.