Calling shell commands from Ruby

2018-12-31 04:48发布

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

20条回答
冷夜・残月
2楼-- · 2018-12-31 04:59

You can also use the backtick operators (`), similar to Perl:

directoryListing = `ls /`
puts directoryListing # prints the contents of the root directory

Handy if you need something simple.

Which method you want to use depends on exactly what you're trying to accomplish; check the docs for more details about the different methods.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 05:01

The way I like to do this is using the %x literal, which makes it easy (and readable!) to use quotes in a command, like so:

directorylist = %x[find . -name '*test.rb' | sort]

Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:

directorylist.each do |filename|
  filename.chomp!
  # work with file
end
查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 05:02

Here's the best article in my opinion about running shell scripts in Ruby: "6 Ways to Run Shell Commands in Ruby".

If you only need to get the output use backticks.

I needed more advanced stuff like STDOUT and STDERR so I used the Open4 gem. You have all the methods explained there.

查看更多
永恒的永恒
5楼-- · 2018-12-31 05:02

Don't forget the spawn command to create a background process to execute the specified command. You can even wait for its completion using the Process class and the returned pid:

pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2")
Process.wait pid

pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'")
Process.wait pid

The doc says: This method is similar to #system but it doesn't wait for the command to finish.

查看更多
初与友歌
6楼-- · 2018-12-31 05:03

easiest way is, for example:

reboot = `init 6`
puts reboot
查看更多
零度萤火
7楼-- · 2018-12-31 05:06

If you really need Bash, per the note in the "best" answer.

First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems.

If you need to use Bash, insert bash -c "your Bash-only command" inside of your desired calling method.

quick_output = system("ls -la")

quick_bash = system("bash -c 'ls -la'")

To test:

system("echo $SHELL") system('bash -c "echo $SHELL"')

Or if you are running an existing script file (eg script_output = system("./my_script.sh")) Ruby should honor the shebang, but you could always use system("bash ./my_script.sh") to make sure (though there may be a slight overhead from /bin/sh running /bin/bash, you probably won't notice.

查看更多
登录 后发表回答