Daniel Watrous
Daniel Watrous

Reputation: 3861

Quote a path in a shell script

I have a shell script that uses base64 to encode a value and store it in a variable.

encoded="$(cat $pathtofile|base64 -w 0)"

This worked until I ended up with a $pathtofile that had a special character in it. Now I'm trying to figure out how to quote the $pathtofile so that cat gets the right file. When I do this

encoded="$(cat '$pathtofile'|base64 -w 0)"

I end up with an error because it doesn't expand $pathtofile, but prints it literally. I have tried several other combinations, but they all result in a misquoted path.

How can I end up with a quoted $pathtofile?

Upvotes: 1

Views: 1621

Answers (1)

John Kugelman
John Kugelman

Reputation: 362157

Double quotes can be nested when you use $(...).

encoded="$(cat "$pathtofile" | base64 -w 0)"

For what it's worth, the outer set of quotes is optional. They're not needed in variable assignments. Remove them if you like.

encoded=$(cat "$pathtofile" | base64 -w 0)

Also, congratulations, you've won a Useless Use of Cat Award!

encoded=$(base64 -w 0 "$pathtofile")

Upvotes: 3

Related Questions