I want to get onre output of top to variable for future processing. I tried:

top=$(top -n1)
top=$(top -n1 -w80)
top=$(top -n1 -b -w80)
top=$(COLUMNS=100 top -b-n1)

When I run echo $top then I see something like on the screenshot enter image description here that is top output completely without line breaks. What am I doing wrong?


Double-quote the variable

try echo "${top}" after assigning top="$(top -n1)"

|improve this answer|||||

Unable to replicate:

$ t="$( top -b -n1 )"
$ echo "$t" | head -n3
top - 14:49:52 up 243 days, 17:18,  2 users,  load average: 0.03, 0.07, 0.12
Tasks: 205 total,   1 running, 203 sleeping,   1 stopped,   0 zombie
%Cpu(s):  2.4 us,  0.5 sy,  0.1 ni, 96.4 id,  0.7 wa,  0.0 hi,  0.0 si,  0.0 st
|improve this answer|||||
  • I think he is seeing the same thing as you based on his screenshot. I'm guessing he only wants the top line? – jesse_b Nov 15 '17 at 21:51
  • 1
    The difference is that in the OP's screen capture, there are no linebreaks. I am unable to replicate this. – DopeGhoti Nov 15 '17 at 21:54
  • 1
    I can replicate that on centos 7. As Andrew pointed out in his answer, the variable must be quoted or it prints as a single line. – jesse_b Nov 15 '17 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.