大网数据广告活动
服务器运维问答

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

· 52CE 我爱测

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 th…

问题原文

原帖链接 · kamokoba · CC BY-SA 4.0

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?

已采纳解答

原帖链接 · Michael Hampton · CC BY-SA 4.0

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 }}$'

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-08-12)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。