1

I have a small script where I appended the output of linux mpstat to a log file.

#/bin/bash
CPU_USAGE=$(mpstat)
echo $CPU_USAGE >> temp.log

The problem is that the output of mpstat on the terminal is formatted properly in 3 lines like so

enter image description here

However, the output to the file is all in one line.

enter image description here

How do I format the output like the one on the terminal?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Monty Swanson
  • 695
  • 16
  • 41

2 Answers2

1

Just quote the variable so it is not seen as several different parameters to be printed one after the other:

echo "$CPU_USAGE" >> temp.log
Poshi
  • 5,332
  • 3
  • 15
  • 32
0

You could just directly pipe the output to the file:

#!/bin/bash
mpstat >> temp.log

If you must store it in a variable, then quote it like:

#!/bin/bash
CPU_USAGE=$(mpstat)
echo "$CPU_USAGE" >> temp.log

Otherwise, bash will not interpret the newlines as part of the message to echo, but the whole output as a list of short strings to output.

Damocles
  • 1,287
  • 1
  • 7
  • 9