Grep output stored in a variable is echoed as a single line without quotes

3 min

language: ja bn en es hi pt ru zh-cn zh-tw

Hello, it's the incompetent me.

This will be quick, but I'm writing it down as a note.


When I echoed the result of grep stored in a variable, it was output without line breaks for some reason.

So, here is the test script.

#!/bin/bash

FILE=nohup.out
## Try putting it in a variable
GR=`grep ACPI $FILE` 

## This outputs it as a single line
echo $GR

echo "-----Above this line is without double quotes. Below is with.------"

## This outputs it with proper newlines
echo "$GR"

Let's try running it.

〜〜〜
complete [65791.702186] ACPI: EC: EC started [65791.702188] ACPI: PM: Restoring platform NVS memory [65791.719207] ACPI: PM: Waking up from system sleep state S3 [65791.728986] ACPI: EC: interrupt unblocked [65791.733283] ACPI: EC: event unblocked [65792.083297] ata1.00: ACPI cmd f5/00:00:00:00:00:a0(SECURITY FREEZE LOCK) filtered out [65792.083311] ata1.00: ACPI cmd ef/10:03:00:00:00:a0(SET FEATURES) filtered out [65792.087153] ata1.00: ACPI cmd f5/00:00:00:00:00:a0(SECURITY FREEZE LOCK) filtered out [65792.087169] ata1.00: ACPI cmd ef/10:03:00:00:00:a0(SET FEATURES) filtered out
-----Above this line is without double quotes. Below is with.------
[    0.184506] pnp: PnP ACPI init
[    0.184506] pnp: PnP ACPI: found 6 devices
[    0.226677] ACPI: AC: AC Adapter [AC] (on-line)
[    0.226787] ACPI: button: Lid Switch [LID]
[    0.226855] ACPI: button: Sleep Button [SLPB]
[    0.226933] ACPI: button: Power Button [PWRF]
〜〜〜

This is dmesg output, so I've omitted some parts, but it looks like the above.

When you want to output it as a single line, you should expand it without quotes; if you want newlines, you should use quotes.


Well, that's all there is to it...

That's all for now.

Looking forward to your continued support.

Related Posts