DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Run Shell Script Inside Ruby Script


Backtick grammar

Thanks to the backtick grammar and string substitution, shell script can be embedded more easily into Ruby script than Python.

Execute shell command in irb, the return value is the output in stdout:

2.1.2 :036 > `ls -l|grep play`
 => "drwxr-xr-x 3 chad chad 4096 Aug 12 17:17 playproj\n" 
 2.1.2 :037 > `aaa`
 Errno::ENOENT: No such file or directory - aaa
 ...

Execute shell commands in Ruby scripts:

# Usage: Save the following scripts in file "cmd.rb" 
$ ruby cmd.rb ls -a 
cmd = ARGV[0] 
op = ARGV[1] 
result = `#{cmd} #{op}` 
puts result

system function

Kernel#system executes the given command in a subshell. Return true if the command was found and ran successfully, false otherwise. The output of the command will be written to stdout. So it can't store the command output.

2.1.2 :036 > `ls -l|grep play`
drwxr-xr-x 3 chad chad 4096 Aug 12 17:17 playproj
 => truee

Ref:

Calling Bash Commands From Ruby

Can Ruby access output from shell commands as it appears?



Published

Dec 2, 2013

Last Updated

Dec 2, 2013

Category

Tech

Tags

  • ruby 9
  • shell 46

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor