【问题标题】:Executing below system command through ruby通过ruby执行以下系统命令
【发布时间】:2014-04-26 10:40:41
【问题描述】:

我正在使用 ruby​​ 执行系统命令。代码是这样的

commandtoexecute=“pararellrspec --type rspec -n 1 --test-options '--test "cases's owner"' testing/multi/getcreate.rb “

system(commandtoexecute)

在执行上述行时,它给出了错误

sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file

但是当我通过用上面的案例替换案例来执行时,它可以工作。有没有人知道如何在不将“cases”替换为“cases”的情况下防止上述错误

【问题讨论】:

  • 你试过转义它`'..."cases\'s owner"...'吗?
  • 不能那样做。字符串 "--test "cases's owner"" 存储在一个变量中,该变量在发出命令时被替换。所以没有办法尝试案例的

标签: ruby macos shell rspec


【解决方案1】:

你需要转义你的双引号:

"pararellrspec --type rspec -n 1 --test-options '--test \"cases's owner\"' testing/multi/getcreate.rb"

编辑:可能那行单引号也是如此,想想看:

"pararellrspec --type rspec -n 1 --test-options '--test \"cases\'s owner\"' testing/multi/getcreate.rb"

或者如果按预期工作,也许删除单引号而不是那个:

"pararellrspec --type rspec -n 1 --test-options --test \"cases's owner\" testing/multi/getcreate.rb"

或者(更好),在适当的时候使用 system 的数组风格,以便让 Ruby 为您处理引用参数:

system("echo *")
system("echo", "*")

http://www.ruby-doc.org/core-2.1.1/Kernel.html#method-i-system

【讨论】:

    【解决方案2】:

    不确定请尝试这样:-

    1.9.3p448 :025 > commandtoexecute="pararellrspec --type rspec -n 1 --test-options '--test 'cases\'s owner' testing/multi/getcreate.rb"
    
      => "pararellrspec --type rspec -n 1 --test-options '--test 'cases's owner' testing/multi/getcreate.rb"
    
    1.9.3p448 :026 > system(commandtoexecute)
    

    这会起作用,请尝试一下。

    click了解更多详情。

    【讨论】:

      【解决方案3】:
      commandtoexecute="pararellrspec --type rspec -n 1 --test-options '--test "cases's owner"' testing/multi/getcreate.rb"
      system(commandtoexecute)
      

      如您所见,您的命令字符串中的 " 和 ' 存在转义问题。要规避此问题,您可以使用

      %x(ruby --copyright)
      > "ruby - Copyright (C) 1993-2013 Yukihiro Matsumoto\n"
      

      在 ruby​​ 中执行 shell 命令。这种速记方法负责任何必要的转义。所以你的原始代码归结为:

      %x(pararellrspec --type rspec -n 1 --test-options '--test "cases's owner"' testing/multi/getcreate.rb)
      

      如您所见,因为您不需要" 来创建一个包含您的命令的字符串(就像您在上面为commandtoexecute 所做的那样),所以转义问题已经消失了。

      【讨论】:

      • 我没听懂……命令应该像 system(%x(commandtoexecute))
      • 不,类似:%x(pararellrspec --type rspec -n 1 --test-options --test "cases's owner" testing/multi/getcreate.rb) 这会将命令作为系统命令执行,并且应该注意正确的转义
      • sry 无法理解这一点。试过 '%x(commandtoexecute)' 和 'system(%x(commandtoexecute))'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多