【问题标题】:Single quotes escaping Ruby转义 Ruby 的单引号
【发布时间】:2018-10-02 18:16:18
【问题描述】:

所以,我正在使用一个 Ruby 脚本,该脚本需要连接到一堆服务器并从中获取信息。我遇到的问题是单引号似乎以某种方式丢失了。我在这里做错了什么?

command = "grep -E \'^(upstream| *server)\'  /etc/nginx/upstreams.conf | sed -E \'s/_pool.*//g ; s/^upstream //g\'"

puts system("ssh -n   -o 'StrictHostKeyChecking no' #{nginx_stage_servers[0]} #{command}")

我得到的错误:

 $ ruby nx.rb
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `grep -E ^(upstream| *server) /etc/nginx/upstreams.conf'
true

错误的原因是缺少单引号。

【问题讨论】:

  • 您是否尝试过使用Kernel#system 的多参数形式来避免不得不处理shell?类似于system('ssh', '-n', '-o', 'StrictHostKeyChecking no', nginx_stage_servers[0], ...)
  • 不。我没有。但我会试试的。谢谢

标签: ruby escaping single-quotes


【解决方案1】:

当你使用system(command_string) 时,你有太多层的引用和转义需要处理,你几乎总是最好使用Kernel#system 的多参数形式来避免处理shell。这样的问题会少一些:

system('ssh', '-n', '-o', 'StrictHostKeyChecking no', nginx_stage_servers[0], command)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多