0

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
  • 77,979
  • 13
  • 71
  • 125
Monty Swanson
  • 588
  • 13
  • 35

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
  • 4,817
  • 3
  • 13
  • 28
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,247
  • 1
  • 4
  • 8