代码之家  ›  专栏  ›  技术社区  ›  paulgreg

是否可以使用反引号将参数连接到命令行?

  •  1
  • paulgreg  · 技术社区  · 16 年前

    我想从我的Ruby脚本执行一个OS命令,但我想从Ruby变量添加一个参数。

    我知道使用关键字是可能的 系统 像这样:

    #!/usr/bin/env ruby
    directory = '/home/paulgreg/'
    system 'ls ' + directory
    

    但使用“反引号或反勾号语法”是否可能实现这一点? (我的意思是使用这种语法: ls )

    3 回复  |  直到 10 年前
        1
  •  6
  •   Jordi Bunster    16 年前

    不,这只是将输出连接到 ls 以及 directory .

    但你可以这样做:

    #!/usr/bin/env ruby
    directory = '/home/paulgreg/'
    `ls #{directory}`
    
        2
  •  6
  •   Nick Brosnahan    16 年前
    `ls #{directory}` 
    

    不太安全,因为您会遇到路径名中有空格的问题。

    这样做比较安全:

    directory = '/home/paulgreg/'
    
    args = []
    args << "/bin/ls"
    args << directory
    
    system(*args)
    
        3
  •  1
  •   0124816    16 年前

    尼克是对的,但不需要分段组装args:

    directory = '/Volumes/Omg a space/'
    system('/bin/ls', directory)