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

时间:2022-10-30 23:17:32

I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.

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

I know that's possible by using keyword system like that :

我知道可以使用这样的关键字系统:

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

but is that possible by using the "backquotes or backticks syntax" ? (I mean by using that syntax : ls)

但这可能是通过使用“反引号或反引号语法”吗? (我的意思是使用该语法:ls)

3 个解决方案

#1


6  

No, that will just concatenate the output from ls and the contents of directory.

不,这只会连接ls的输出和目录的内容。

But you can do this:

但是你可以这样做:

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`

#2


6  

`ls #{directory}` 

isn't very safe because you're going to run into problems with path names that have spaces in them.

是不是很安全,因为你将遇到包含空格的路径名的问题。

It's safer to do something like this:

做这样的事更安全:

directory = '/home/paulgreg/'

args = []
args << "/bin/ls"
args << directory

system(*args)

#3


1  

Nick is right, but there is no need to assemble the args piecewise:

尼克是对的,但没有必要分段组装args:

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

#1


6  

No, that will just concatenate the output from ls and the contents of directory.

不,这只会连接ls的输出和目录的内容。

But you can do this:

但是你可以这样做:

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`

#2


6  

`ls #{directory}` 

isn't very safe because you're going to run into problems with path names that have spaces in them.

是不是很安全,因为你将遇到包含空格的路径名的问题。

It's safer to do something like this:

做这样的事更安全:

directory = '/home/paulgreg/'

args = []
args << "/bin/ls"
args << directory

system(*args)

#3


1  

Nick is right, but there is no need to assemble the args piecewise:

尼克是对的,但没有必要分段组装args:

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