Geoffrey Garbers Thoughts on everything from PHP to photography

Preserving whitespace in bash variables

Posted 3 months from now.

I’ve been creating some bash scripts for an importer we are running at work. I was looking to do two things with this. Firstly, I wanted to brush up on my knowledge of bash scripting. Secondly, I wanted to improve the notifications sent out from the importer.

I managed to get everything working fine. Except for the simple fact that all of the whitespace was being stripped from the variable that received the command’s output. I searched absolutely everywhere for someone else that was experiencing this same issue. Finally, I found someone else that was experiencing the same thing.

This is how I was reading and displaying the output initially:

CMD_OUTPUT=`/usr/bin/php runImporter.php`
echo $CMD_OUTPUT

And this is how the output was being displayed:

Updating core XML: ------------------------------------------------------------------------ Creating temporary download file... [OK] Downloading ZIP archive... [OK] Extracting ZIP archive... [OK] Checking for valid extracted file... [OK] Validating XML integrity... [OK] Archiving current XML file... [OK] Updating live XML file... [OK]

The Solution?

The solution is really simple – all you need to do is wrap the $CMD_OUTPUT variable in double quotes (“). So, to apply this to the script shown above:

CMD_OUTPUT=`/usr/bin/php runImporter.php`
echo "$CMD_OUTPUT"

Which will give you this:

Updating core XML:
------------------------------------------------------------------------
Creating temporary download file... [OK]
Downloading ZIP archive... [OK]
Extracting ZIP archive... [OK]
Checking for valid extracted file... [OK]
Validating XML integrity... [OK]
Archiving current XML file... [OK]
Updating live XML file... [OK]

Like I said, it’s a super simple solution to a really frustrating problem. Many thanks to Mike Zupan for this blog post that solved this for me.

Comments

Milos 4 months ago
I figured this out myself a couple of months back. I recently returned to some of my scripts, to spruce them up a bit, and I hit a wall when my output returned garbled.

A quick google search led me here, and your text reminded me of the solution :)

Thanks!
Geoff Garbers 3 months ago
Awesome. Glad to be of help :)

Leave a reply

Your email address will not be published. Required fields are marked *