简体   繁体   English

如何从ruby文件中运行命令行命令?

[英]How can I run a command line command from within a ruby file?

I have a gem installed that displays a ascii image of a train moving across the terminal screen when someone types "ls". 我安装了一个gem,当有人键入“ ls”时,它会显示在终端屏幕上移动的火车的ascii图像。 I also have a file called runner.rb. 我还有一个名为Runner.rb的文件。

If it's possible, how can I input the "ls" command to the terminal from within the ruby file? 如果可能,如何从ruby文件中向终端输入“ ls”命令?

cmd = "ls > somefile.txt"
system( cmd )

or even just simply 甚至只是

system( "ls" )

Thus, you can use system. 因此,您可以使用系统。

You can also use ( ` ) character to execute Linux commands from ruby file. 您也可以使用( ` )字符从ruby文件执行Linux命令。

eg 例如

`ls` ## OR `whoami` etc.

If you want to execute the command as if you were sitting in the shell (so its output displays, etc.), use system . 如果要像坐在外壳中一样执行命令(因此将显示其输出等),请使用system

> system('ls')
Look        At        All
My          Cool      Files
=> true

If you want to capture the output for use, use backticks. 如果要捕获输出以供使用,请使用反引号。

> files = `ls`
=> "Look\nAt\nAll\nMy\nCool\nFiles\n"

You can interpolate in backticks if you want to (and obviously in the string you pass to system ). 如果需要,您可以插反引号(显然是在传递给system的字符串中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM