Do you enjoy escaping quotes inside strings? I sure don’t, and I really appreciate the flexibility CFEngine provides with 3 different quoting characters ("
, '
, `
). Let’s take a look.
This came up in the post show discussion for The agent is in, episode 39.
If you have a string that contains double quotes you might see it written with escaped quotes like this:
bundle agent __main__
{
vars:
"my_string_contains_escaped_double_quotes"
string => "I \"hate\" escaping quotes";
reports:
"$(my_string_contains_escaped_double_quotes)";
}
# cf-agent --no-lock --file /tmp/feature-friday-41-0.cf
R: I "hate" escaping quotes
CFEngine also supports single quotes ('
) which allows you to avoid escaping:
bundle agent __main__
{
vars:
"my_string_contains_double_quotes"
string => 'I "hate" escaping quotes';
reports:
"$(my_string_contains_double_quotes)";
}
# cf-agent --no-lock --file /tmp/feature-friday-41-1.cf
R: I "hate" escaping quotes
There is however the occasion where you need both single and double quotes within a string. When that is the case it’s a really good time to remember that CFEngine also recognizes backticks (`
) as a quoting symbol.
bundle agent __main__
{
vars:
"my_string_contains_single_and_double_quotes"
string => `'I "hate" escaping quotes'`;
reports:
"I said $(my_string_contains_single_and_double_quotes)!";
}
# cf-agent --no-lock --file /tmp/feature-friday-41-2.cf
R: I said 'I "hate" escaping quotes'!
Of course you can change the order around for your needs as we see in this next example:
bundle agent __main__
{
vars:
"my_string_contains_single_and_double_quotes"
string => `"I 'hate' escaping quotes"`;
"my_string_contains_backticks_and_double_quotes"
string => '"I `hate` escaping quotes"';
reports:
"Have I mentioned $(my_string_contains_single_and_double_quotes)?";
"Yes, really, $(my_string_contains_backticks_and_double_quotes).";
}
# cf-agent --no-lock --file /tmp/feature-friday-41-3.cf
R: Have I mentioned "I 'hate' escaping quotes"?
R: Yes, really, "I `hate` escaping quotes".
I hope you enjoyed this tip more than you enjoy escaping quotes.
Happy Friday! 🎉