HardcoreHenry
HardcoreHenry

Reputation: 6377

bash how to quote string with quotes

I want to synchronize some environment variables between scripts. So, for example, in one script I might have:

foo="some value with \"quoted part\""
echo foo="$foo" > tmp.sh;

Then in the other script, I want to run ./tmp.sh. The issue is with whitespace and quotes. The tmp.sh script contains:

foo=string with "quoted part"

Which does not work due to the whitespace. If I use \"'s then it results in:

foo="string with "quoted part""

which fails because now the space inside the quotes looks like its outside of quotes. What I want is:

foo="string with \"quoted part\""

Of course, it should handle already escaped quotes, etc. Is there any reliable way of quoting a string in bash so it can be used for an assignment later on?

Upvotes: 0

Views: 146

Answers (1)

chepner
chepner

Reputation: 530940

Use printf '%q':

$ printf 'foo=%q\n'  "$foo"
foo=some\ value\ with\ \"quoted\ part\"

It looks slightly different, but it has the same effect; the backslashes individually quote each character that needs escaping, rather than escaping the entire string unnecessarily (since, for instance, \v and v are the same character).

Upvotes: 3

Related Questions