How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
相关问题
- How to get the return code of a shell script in lu
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- Invoking Mirth Connect CLI with Powershell script
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Ruby using wrong version of openssl
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
You can also use the backtick operators (`), similar to Perl:
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.
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:Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:
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.
Don't forget the
spawn
command to create a background process to execute the specified command. You can even wait for its completion using theProcess
class and the returnedpid
:The doc says: This method is similar to
#system
but it doesn't wait for the command to finish.easiest way is, for example:
If you really need Bash, per the note in the "best" answer.
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 usesystem("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.