0

I can run a ruby script via command line via ruby 'name of file'

In that file, I can do `puts "this_and_that_string"

But how do I make a string I put together behave as if I typed them into the command line directly, to execute commands?

e.g. some_function cd \/var\/ within the ruby script to behave as if I typed into the command line: cd /var

ahnbizcad
  • 10,491
  • 9
  • 59
  • 85

2 Answers2

1

You can use backticks or system to access shell commands:

system 'cd /var/'

You’ll notice some difference in what they return (string vs exit status) and print.

But note that there are Ruby functions that already do some of the things you might be trying to do with the shell, e.g., Dir.chdir. In fact, the shell-outs mentioned above start a single subprocess that will lose track of having cd’d into a dir. So you’d have to string together commands that include a starting cd, like:

system 'cd /var; ls'
Micah Elliott
  • 9,600
  • 5
  • 51
  • 54
1

The short answer is use backticks in your ruby code to shell out to the command line. A good explanation of that is posted here: Calling shell commands from Ruby

Community
  • 1
  • 1
grenierm5
  • 186
  • 4
  • 14