Score:1

Ansible 2.9.21: unwanted escape char “\” is added in shell command

cn flag

In my playbook the following line should return 1, and if it returns >1, the play should stop:

shell: ls -l /opt/tomcat/|grep "[ ]\+{{ newTomcatVer }}$"; echo $?

My play did indeed fail with this error:

"msg": "There is more than one /opt/tomcat/apache-tomcat-8.x.xx instance on server01, ending play"

After running again with in debug mode, I see this shell command is being represented like this in the debug output:

"cmd": "ls -l /opt/tomcat/|grep \"[ ]\\+apache-tomcat-8.5.69$\"; echo $?",

In the above, double quotes are escaped with \ character. The question is, which command is actually being used - the one that is in the playbook, or the one which we see in the debug output?

Because if I run the command which is in the notebook, i.e. without escape chars, the output is 1 as expected:

[tomcat@server01 ~]$ ls -l /opt/tomcat/|grep "[ ]\\+apache-tomcat-8.5.69$"; echo $?
1

But if I issue the command which is in the debug output, I get this:

[tomcat@server01 ~]$ ls -l /opt/tomcat/|grep \"[ ]\\+apache-tomcat-8.5.69$\"; echo $?
grep: Invalid regular expression
2

Any ideas how to solve this?

Score:2
cz flag

Use single quotes in the grep command.

grep "[ ]\+{{ newTomcatVer }}$"

When you use double quotes, the shell will try to do variable expansion, meaning it will try to make sense of $". This is coming out as $\" because the shell doesn't recognize $" as a parameter it can expand, so it tries to guess what you wanted and escapes the quotation mark.

There's no real reason to do shell parameter expansion here, so you can place the regex in single quotes to solve the problem. The shell will not attempt to do parameter expansion and will treat the $ literally.

grep '[ ]\+{{ newTomcatVer }}$'
cn flag
But my question is, what if newTomcatVer itself contains a single quote? How that would be handled?
cn flag
I think I've found my question answered in https://stackoverflow.com/a/56026662/1449366
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.